From 8b4f8a0f1afb477c10a2b6be710a55abda549c1c Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 23 Jul 2021 21:10:25 +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 + owl-bot-staging/v1/docs/conf.py | 376 ++ .../v1/docs/grafeas_v1/grafeas.rst | 10 + .../v1/docs/grafeas_v1/services.rst | 6 + owl-bot-staging/v1/docs/grafeas_v1/types.rst | 7 + owl-bot-staging/v1/docs/index.rst | 7 + .../v1/grafeas/grafeas/__init__.py | 149 + owl-bot-staging/v1/grafeas/grafeas/py.typed | 2 + .../v1/grafeas/grafeas_v1/__init__.py | 150 + .../v1/grafeas/grafeas_v1/gapic_metadata.json | 163 + .../v1/grafeas/grafeas_v1/py.typed | 2 + .../grafeas/grafeas_v1/services/__init__.py | 15 + .../grafeas_v1/services/grafeas/__init__.py | 22 + .../services/grafeas/async_client.py | 1415 +++++ .../grafeas_v1/services/grafeas/client.py | 1567 ++++++ .../grafeas_v1/services/grafeas/pagers.py | 384 ++ .../services/grafeas/transports/__init__.py | 33 + .../services/grafeas/transports/base.py | 406 ++ .../services/grafeas/transports/grpc.py | 613 ++ .../grafeas/transports/grpc_asyncio.py | 617 ++ .../v1/grafeas/grafeas_v1/types/__init__.py | 168 + .../grafeas/grafeas_v1/types/attestation.py | 109 + .../v1/grafeas/grafeas_v1/types/build.py | 79 + .../v1/grafeas/grafeas_v1/types/common.py | 133 + .../v1/grafeas/grafeas_v1/types/cvss.py | 154 + .../v1/grafeas/grafeas_v1/types/deployment.py | 109 + .../v1/grafeas/grafeas_v1/types/discovery.py | 113 + .../v1/grafeas/grafeas_v1/types/grafeas.py | 768 +++ .../v1/grafeas/grafeas_v1/types/image.py | 153 + .../v1/grafeas/grafeas_v1/types/package.py | 230 + .../v1/grafeas/grafeas_v1/types/provenance.py | 528 ++ .../v1/grafeas/grafeas_v1/types/upgrade.py | 261 + .../grafeas/grafeas_v1/types/vulnerability.py | 424 ++ owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 132 + .../v1/scripts/fixup_grafeas_v1_keywords.py | 189 + 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 + .../tests/unit/gapic/grafeas_v1/__init__.py | 16 + .../unit/gapic/grafeas_v1/test_grafeas.py | 4957 +++++++++++++++++ 44 files changed, 14640 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/grafeas_v1/grafeas.rst create mode 100644 owl-bot-staging/v1/docs/grafeas_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/grafeas_v1/types.rst create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/grafeas/grafeas/__init__.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas/py.typed create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/__init__.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/py.typed create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/__init__.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/async_client.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/client.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/pagers.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/__init__.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/base.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/attestation.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/build.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/common.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/cvss.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/deployment.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/discovery.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/grafeas.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/image.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/package.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/provenance.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/upgrade.py create mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/vulnerability.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_grafeas_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/grafeas_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/grafeas_v1/test_grafeas.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 0000000..e619077 --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + grafeas/grafeas/__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 0000000..075904e --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include grafeas/grafeas *.py +recursive-include grafeas/grafeas_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 0000000..0f87949 --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Grafeas Grafeas 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 Grafeas Grafeas API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 0000000..c3771e8 --- /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. +# +# +# grafeas-grafeas 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"grafeas-grafeas" +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": "Grafeas 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 = "grafeas-grafeas-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, + "grafeas-grafeas.tex", + u"grafeas-grafeas 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, + "grafeas-grafeas", + u"Grafeas Grafeas 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, + "grafeas-grafeas", + u"grafeas-grafeas Documentation", + author, + "grafeas-grafeas", + "GAPIC library for Grafeas Grafeas 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/grafeas_v1/grafeas.rst b/owl-bot-staging/v1/docs/grafeas_v1/grafeas.rst new file mode 100644 index 0000000..7339fab --- /dev/null +++ b/owl-bot-staging/v1/docs/grafeas_v1/grafeas.rst @@ -0,0 +1,10 @@ +Grafeas +------------------------- + +.. automodule:: grafeas.grafeas_v1.services.grafeas + :members: + :inherited-members: + +.. automodule:: grafeas.grafeas_v1.services.grafeas.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/grafeas_v1/services.rst b/owl-bot-staging/v1/docs/grafeas_v1/services.rst new file mode 100644 index 0000000..ca38222 --- /dev/null +++ b/owl-bot-staging/v1/docs/grafeas_v1/services.rst @@ -0,0 +1,6 @@ +Services for Grafeas Grafeas v1 API +=================================== +.. toctree:: + :maxdepth: 2 + + grafeas diff --git a/owl-bot-staging/v1/docs/grafeas_v1/types.rst b/owl-bot-staging/v1/docs/grafeas_v1/types.rst new file mode 100644 index 0000000..91237ff --- /dev/null +++ b/owl-bot-staging/v1/docs/grafeas_v1/types.rst @@ -0,0 +1,7 @@ +Types for Grafeas Grafeas v1 API +================================ + +.. automodule:: grafeas.grafeas_v1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 0000000..e0393b8 --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + grafeas_v1/services + grafeas_v1/types diff --git a/owl-bot-staging/v1/grafeas/grafeas/__init__.py b/owl-bot-staging/v1/grafeas/grafeas/__init__.py new file mode 100644 index 0000000..0d45ec6 --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas/__init__.py @@ -0,0 +1,149 @@ +# -*- 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 grafeas.grafeas_v1.services.grafeas.client import GrafeasClient +from grafeas.grafeas_v1.services.grafeas.async_client import GrafeasAsyncClient + +from grafeas.grafeas_v1.types.attestation import AttestationNote +from grafeas.grafeas_v1.types.attestation import AttestationOccurrence +from grafeas.grafeas_v1.types.build import BuildNote +from grafeas.grafeas_v1.types.build import BuildOccurrence +from grafeas.grafeas_v1.types.common import RelatedUrl +from grafeas.grafeas_v1.types.common import Signature +from grafeas.grafeas_v1.types.common import NoteKind +from grafeas.grafeas_v1.types.cvss import CVSSv3 +from grafeas.grafeas_v1.types.deployment import DeploymentNote +from grafeas.grafeas_v1.types.deployment import DeploymentOccurrence +from grafeas.grafeas_v1.types.discovery import DiscoveryNote +from grafeas.grafeas_v1.types.discovery import DiscoveryOccurrence +from grafeas.grafeas_v1.types.grafeas import BatchCreateNotesRequest +from grafeas.grafeas_v1.types.grafeas import BatchCreateNotesResponse +from grafeas.grafeas_v1.types.grafeas import BatchCreateOccurrencesRequest +from grafeas.grafeas_v1.types.grafeas import BatchCreateOccurrencesResponse +from grafeas.grafeas_v1.types.grafeas import CreateNoteRequest +from grafeas.grafeas_v1.types.grafeas import CreateOccurrenceRequest +from grafeas.grafeas_v1.types.grafeas import DeleteNoteRequest +from grafeas.grafeas_v1.types.grafeas import DeleteOccurrenceRequest +from grafeas.grafeas_v1.types.grafeas import GetNoteRequest +from grafeas.grafeas_v1.types.grafeas import GetOccurrenceNoteRequest +from grafeas.grafeas_v1.types.grafeas import GetOccurrenceRequest +from grafeas.grafeas_v1.types.grafeas import ListNoteOccurrencesRequest +from grafeas.grafeas_v1.types.grafeas import ListNoteOccurrencesResponse +from grafeas.grafeas_v1.types.grafeas import ListNotesRequest +from grafeas.grafeas_v1.types.grafeas import ListNotesResponse +from grafeas.grafeas_v1.types.grafeas import ListOccurrencesRequest +from grafeas.grafeas_v1.types.grafeas import ListOccurrencesResponse +from grafeas.grafeas_v1.types.grafeas import Note +from grafeas.grafeas_v1.types.grafeas import Occurrence +from grafeas.grafeas_v1.types.grafeas import UpdateNoteRequest +from grafeas.grafeas_v1.types.grafeas import UpdateOccurrenceRequest +from grafeas.grafeas_v1.types.image import Fingerprint +from grafeas.grafeas_v1.types.image import ImageNote +from grafeas.grafeas_v1.types.image import ImageOccurrence +from grafeas.grafeas_v1.types.image import Layer +from grafeas.grafeas_v1.types.package import Distribution +from grafeas.grafeas_v1.types.package import Location +from grafeas.grafeas_v1.types.package import PackageNote +from grafeas.grafeas_v1.types.package import PackageOccurrence +from grafeas.grafeas_v1.types.package import Version +from grafeas.grafeas_v1.types.package import Architecture +from grafeas.grafeas_v1.types.provenance import AliasContext +from grafeas.grafeas_v1.types.provenance import Artifact +from grafeas.grafeas_v1.types.provenance import BuildProvenance +from grafeas.grafeas_v1.types.provenance import CloudRepoSourceContext +from grafeas.grafeas_v1.types.provenance import Command +from grafeas.grafeas_v1.types.provenance import FileHashes +from grafeas.grafeas_v1.types.provenance import GerritSourceContext +from grafeas.grafeas_v1.types.provenance import GitSourceContext +from grafeas.grafeas_v1.types.provenance import Hash +from grafeas.grafeas_v1.types.provenance import ProjectRepoId +from grafeas.grafeas_v1.types.provenance import RepoId +from grafeas.grafeas_v1.types.provenance import Source +from grafeas.grafeas_v1.types.provenance import SourceContext +from grafeas.grafeas_v1.types.upgrade import UpgradeDistribution +from grafeas.grafeas_v1.types.upgrade import UpgradeNote +from grafeas.grafeas_v1.types.upgrade import UpgradeOccurrence +from grafeas.grafeas_v1.types.upgrade import WindowsUpdate +from grafeas.grafeas_v1.types.vulnerability import VulnerabilityNote +from grafeas.grafeas_v1.types.vulnerability import VulnerabilityOccurrence +from grafeas.grafeas_v1.types.vulnerability import Severity + +__all__ = ('GrafeasClient', + 'GrafeasAsyncClient', + 'AttestationNote', + 'AttestationOccurrence', + 'BuildNote', + 'BuildOccurrence', + 'RelatedUrl', + 'Signature', + 'NoteKind', + 'CVSSv3', + 'DeploymentNote', + 'DeploymentOccurrence', + 'DiscoveryNote', + 'DiscoveryOccurrence', + 'BatchCreateNotesRequest', + 'BatchCreateNotesResponse', + 'BatchCreateOccurrencesRequest', + 'BatchCreateOccurrencesResponse', + 'CreateNoteRequest', + 'CreateOccurrenceRequest', + 'DeleteNoteRequest', + 'DeleteOccurrenceRequest', + 'GetNoteRequest', + 'GetOccurrenceNoteRequest', + 'GetOccurrenceRequest', + 'ListNoteOccurrencesRequest', + 'ListNoteOccurrencesResponse', + 'ListNotesRequest', + 'ListNotesResponse', + 'ListOccurrencesRequest', + 'ListOccurrencesResponse', + 'Note', + 'Occurrence', + 'UpdateNoteRequest', + 'UpdateOccurrenceRequest', + 'Fingerprint', + 'ImageNote', + 'ImageOccurrence', + 'Layer', + 'Distribution', + 'Location', + 'PackageNote', + 'PackageOccurrence', + 'Version', + 'Architecture', + 'AliasContext', + 'Artifact', + 'BuildProvenance', + 'CloudRepoSourceContext', + 'Command', + 'FileHashes', + 'GerritSourceContext', + 'GitSourceContext', + 'Hash', + 'ProjectRepoId', + 'RepoId', + 'Source', + 'SourceContext', + 'UpgradeDistribution', + 'UpgradeNote', + 'UpgradeOccurrence', + 'WindowsUpdate', + 'VulnerabilityNote', + 'VulnerabilityOccurrence', + 'Severity', +) diff --git a/owl-bot-staging/v1/grafeas/grafeas/py.typed b/owl-bot-staging/v1/grafeas/grafeas/py.typed new file mode 100644 index 0000000..846a558 --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The grafeas-grafeas package uses inline types. diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/__init__.py b/owl-bot-staging/v1/grafeas/grafeas_v1/__init__.py new file mode 100644 index 0000000..18faedb --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/__init__.py @@ -0,0 +1,150 @@ +# -*- 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.grafeas import GrafeasClient +from .services.grafeas import GrafeasAsyncClient + +from .types.attestation import AttestationNote +from .types.attestation import AttestationOccurrence +from .types.build import BuildNote +from .types.build import BuildOccurrence +from .types.common import RelatedUrl +from .types.common import Signature +from .types.common import NoteKind +from .types.cvss import CVSSv3 +from .types.deployment import DeploymentNote +from .types.deployment import DeploymentOccurrence +from .types.discovery import DiscoveryNote +from .types.discovery import DiscoveryOccurrence +from .types.grafeas import BatchCreateNotesRequest +from .types.grafeas import BatchCreateNotesResponse +from .types.grafeas import BatchCreateOccurrencesRequest +from .types.grafeas import BatchCreateOccurrencesResponse +from .types.grafeas import CreateNoteRequest +from .types.grafeas import CreateOccurrenceRequest +from .types.grafeas import DeleteNoteRequest +from .types.grafeas import DeleteOccurrenceRequest +from .types.grafeas import GetNoteRequest +from .types.grafeas import GetOccurrenceNoteRequest +from .types.grafeas import GetOccurrenceRequest +from .types.grafeas import ListNoteOccurrencesRequest +from .types.grafeas import ListNoteOccurrencesResponse +from .types.grafeas import ListNotesRequest +from .types.grafeas import ListNotesResponse +from .types.grafeas import ListOccurrencesRequest +from .types.grafeas import ListOccurrencesResponse +from .types.grafeas import Note +from .types.grafeas import Occurrence +from .types.grafeas import UpdateNoteRequest +from .types.grafeas import UpdateOccurrenceRequest +from .types.image import Fingerprint +from .types.image import ImageNote +from .types.image import ImageOccurrence +from .types.image import Layer +from .types.package import Distribution +from .types.package import Location +from .types.package import PackageNote +from .types.package import PackageOccurrence +from .types.package import Version +from .types.package import Architecture +from .types.provenance import AliasContext +from .types.provenance import Artifact +from .types.provenance import BuildProvenance +from .types.provenance import CloudRepoSourceContext +from .types.provenance import Command +from .types.provenance import FileHashes +from .types.provenance import GerritSourceContext +from .types.provenance import GitSourceContext +from .types.provenance import Hash +from .types.provenance import ProjectRepoId +from .types.provenance import RepoId +from .types.provenance import Source +from .types.provenance import SourceContext +from .types.upgrade import UpgradeDistribution +from .types.upgrade import UpgradeNote +from .types.upgrade import UpgradeOccurrence +from .types.upgrade import WindowsUpdate +from .types.vulnerability import VulnerabilityNote +from .types.vulnerability import VulnerabilityOccurrence +from .types.vulnerability import Severity + +__all__ = ( + 'GrafeasAsyncClient', +'AliasContext', +'Architecture', +'Artifact', +'AttestationNote', +'AttestationOccurrence', +'BatchCreateNotesRequest', +'BatchCreateNotesResponse', +'BatchCreateOccurrencesRequest', +'BatchCreateOccurrencesResponse', +'BuildNote', +'BuildOccurrence', +'BuildProvenance', +'CVSSv3', +'CloudRepoSourceContext', +'Command', +'CreateNoteRequest', +'CreateOccurrenceRequest', +'DeleteNoteRequest', +'DeleteOccurrenceRequest', +'DeploymentNote', +'DeploymentOccurrence', +'DiscoveryNote', +'DiscoveryOccurrence', +'Distribution', +'FileHashes', +'Fingerprint', +'GerritSourceContext', +'GetNoteRequest', +'GetOccurrenceNoteRequest', +'GetOccurrenceRequest', +'GitSourceContext', +'GrafeasClient', +'Hash', +'ImageNote', +'ImageOccurrence', +'Layer', +'ListNoteOccurrencesRequest', +'ListNoteOccurrencesResponse', +'ListNotesRequest', +'ListNotesResponse', +'ListOccurrencesRequest', +'ListOccurrencesResponse', +'Location', +'Note', +'NoteKind', +'Occurrence', +'PackageNote', +'PackageOccurrence', +'ProjectRepoId', +'RelatedUrl', +'RepoId', +'Severity', +'Signature', +'Source', +'SourceContext', +'UpdateNoteRequest', +'UpdateOccurrenceRequest', +'UpgradeDistribution', +'UpgradeNote', +'UpgradeOccurrence', +'Version', +'VulnerabilityNote', +'VulnerabilityOccurrence', +'WindowsUpdate', +) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/gapic_metadata.json b/owl-bot-staging/v1/grafeas/grafeas_v1/gapic_metadata.json new file mode 100644 index 0000000..77f5ac0 --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/gapic_metadata.json @@ -0,0 +1,163 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "grafeas.grafeas_v1", + "protoPackage": "grafeas.v1", + "schema": "1.0", + "services": { + "Grafeas": { + "clients": { + "grpc": { + "libraryClient": "GrafeasClient", + "rpcs": { + "BatchCreateNotes": { + "methods": [ + "batch_create_notes" + ] + }, + "BatchCreateOccurrences": { + "methods": [ + "batch_create_occurrences" + ] + }, + "CreateNote": { + "methods": [ + "create_note" + ] + }, + "CreateOccurrence": { + "methods": [ + "create_occurrence" + ] + }, + "DeleteNote": { + "methods": [ + "delete_note" + ] + }, + "DeleteOccurrence": { + "methods": [ + "delete_occurrence" + ] + }, + "GetNote": { + "methods": [ + "get_note" + ] + }, + "GetOccurrence": { + "methods": [ + "get_occurrence" + ] + }, + "GetOccurrenceNote": { + "methods": [ + "get_occurrence_note" + ] + }, + "ListNoteOccurrences": { + "methods": [ + "list_note_occurrences" + ] + }, + "ListNotes": { + "methods": [ + "list_notes" + ] + }, + "ListOccurrences": { + "methods": [ + "list_occurrences" + ] + }, + "UpdateNote": { + "methods": [ + "update_note" + ] + }, + "UpdateOccurrence": { + "methods": [ + "update_occurrence" + ] + } + } + }, + "grpc-async": { + "libraryClient": "GrafeasAsyncClient", + "rpcs": { + "BatchCreateNotes": { + "methods": [ + "batch_create_notes" + ] + }, + "BatchCreateOccurrences": { + "methods": [ + "batch_create_occurrences" + ] + }, + "CreateNote": { + "methods": [ + "create_note" + ] + }, + "CreateOccurrence": { + "methods": [ + "create_occurrence" + ] + }, + "DeleteNote": { + "methods": [ + "delete_note" + ] + }, + "DeleteOccurrence": { + "methods": [ + "delete_occurrence" + ] + }, + "GetNote": { + "methods": [ + "get_note" + ] + }, + "GetOccurrence": { + "methods": [ + "get_occurrence" + ] + }, + "GetOccurrenceNote": { + "methods": [ + "get_occurrence_note" + ] + }, + "ListNoteOccurrences": { + "methods": [ + "list_note_occurrences" + ] + }, + "ListNotes": { + "methods": [ + "list_notes" + ] + }, + "ListOccurrences": { + "methods": [ + "list_occurrences" + ] + }, + "UpdateNote": { + "methods": [ + "update_note" + ] + }, + "UpdateOccurrence": { + "methods": [ + "update_occurrence" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/py.typed b/owl-bot-staging/v1/grafeas/grafeas_v1/py.typed new file mode 100644 index 0000000..846a558 --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The grafeas-grafeas package uses inline types. diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/services/__init__.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/__init__.py new file mode 100644 index 0000000..4de6597 --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_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/grafeas/grafeas_v1/services/grafeas/__init__.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/__init__.py new file mode 100644 index 0000000..8ac3361 --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/__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 GrafeasClient +from .async_client import GrafeasAsyncClient + +__all__ = ( + 'GrafeasClient', + 'GrafeasAsyncClient', +) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/async_client.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/async_client.py new file mode 100644 index 0000000..fdf1594 --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/async_client.py @@ -0,0 +1,1415 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from grafeas.grafeas_v1.services.grafeas import pagers +from grafeas.grafeas_v1.types import attestation +from grafeas.grafeas_v1.types import build +from grafeas.grafeas_v1.types import common +from grafeas.grafeas_v1.types import deployment +from grafeas.grafeas_v1.types import discovery +from grafeas.grafeas_v1.types import grafeas +from grafeas.grafeas_v1.types import image +from grafeas.grafeas_v1.types import package +from grafeas.grafeas_v1.types import upgrade +from grafeas.grafeas_v1.types import vulnerability +from .transports.base import GrafeasTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import GrafeasGrpcAsyncIOTransport +from .client import GrafeasClient + + +class GrafeasAsyncClient: + """`Grafeas `__ API. + + Retrieves analysis results of Cloud components such as Docker + container images. + + Analysis results are stored as a series of occurrences. An + ``Occurrence`` contains information about a specific analysis + instance on a resource. An occurrence refers to a ``Note``. A note + contains details describing the analysis and is generally stored in + a separate project, called a ``Provider``. Multiple occurrences can + refer to the same note. + + For example, an SSL vulnerability could affect multiple images. In + this case, there would be one note for the vulnerability and an + occurrence for each image with the vulnerability referring to that + note. + """ + + _client: GrafeasClient + + DEFAULT_ENDPOINT = GrafeasClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = GrafeasClient.DEFAULT_MTLS_ENDPOINT + + note_path = staticmethod(GrafeasClient.note_path) + parse_note_path = staticmethod(GrafeasClient.parse_note_path) + occurrence_path = staticmethod(GrafeasClient.occurrence_path) + parse_occurrence_path = staticmethod(GrafeasClient.parse_occurrence_path) + project_path = staticmethod(GrafeasClient.project_path) + parse_project_path = staticmethod(GrafeasClient.parse_project_path) + common_billing_account_path = staticmethod(GrafeasClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(GrafeasClient.parse_common_billing_account_path) + common_folder_path = staticmethod(GrafeasClient.common_folder_path) + parse_common_folder_path = staticmethod(GrafeasClient.parse_common_folder_path) + common_organization_path = staticmethod(GrafeasClient.common_organization_path) + parse_common_organization_path = staticmethod(GrafeasClient.parse_common_organization_path) + common_project_path = staticmethod(GrafeasClient.common_project_path) + parse_common_project_path = staticmethod(GrafeasClient.parse_common_project_path) + common_location_path = staticmethod(GrafeasClient.common_location_path) + parse_common_location_path = staticmethod(GrafeasClient.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: + GrafeasAsyncClient: The constructed client. + """ + return GrafeasClient.from_service_account_info.__func__(GrafeasAsyncClient, 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: + GrafeasAsyncClient: The constructed client. + """ + return GrafeasClient.from_service_account_file.__func__(GrafeasAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> GrafeasTransport: + """Returns the transport used by the client instance. + + Returns: + GrafeasTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(GrafeasClient).get_transport_class, type(GrafeasClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, GrafeasTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the grafeas 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, ~.GrafeasTransport]): 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 = GrafeasClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_occurrence(self, + request: grafeas.GetOccurrenceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.Occurrence: + r"""Gets the specified occurrence. + + Args: + request (:class:`grafeas.grafeas_v1.types.GetOccurrenceRequest`): + The request object. Request to get an occurrence. + name (:class:`str`): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + # 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 = grafeas.GetOccurrenceRequest(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_occurrence, + 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=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_occurrences(self, + request: grafeas.ListOccurrencesRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListOccurrencesAsyncPager: + r"""Lists occurrences for the specified project. + + Args: + request (:class:`grafeas.grafeas_v1.types.ListOccurrencesRequest`): + The request object. Request to list occurrences. + parent (:class:`str`): + The name of the project to list occurrences for in the + form of ``projects/[PROJECT_ID]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + The filter expression. + 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: + grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesAsyncPager: + Response for listing occurrences. + 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, 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 = grafeas.ListOccurrencesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + 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_occurrences, + 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=30.0, + ), + default_timeout=30.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.ListOccurrencesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_occurrence(self, + request: grafeas.DeleteOccurrenceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified occurrence. For example, use + this method to delete an occurrence when the occurrence + is no longer applicable for the given resource. + + Args: + request (:class:`grafeas.grafeas_v1.types.DeleteOccurrenceRequest`): + The request object. Request to delete an occurrence. + name (:class:`str`): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # 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 = grafeas.DeleteOccurrenceRequest(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_occurrence, + 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=30.0, + ), + default_timeout=30.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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_occurrence(self, + request: grafeas.CreateOccurrenceRequest = None, + *, + parent: str = None, + occurrence: grafeas.Occurrence = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.Occurrence: + r"""Creates a new occurrence. + + Args: + request (:class:`grafeas.grafeas_v1.types.CreateOccurrenceRequest`): + The request object. Request to create a new occurrence. + parent (:class:`str`): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrence is + to be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrence (:class:`grafeas.grafeas_v1.types.Occurrence`): + The occurrence to create. + This corresponds to the ``occurrence`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + # 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, occurrence]) + if request is 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 = grafeas.CreateOccurrenceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if occurrence is not None: + request.occurrence = occurrence + + # 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_occurrence, + default_timeout=30.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, + ) + + # Done; return the response. + return response + + async def batch_create_occurrences(self, + request: grafeas.BatchCreateOccurrencesRequest = None, + *, + parent: str = None, + occurrences: Sequence[grafeas.Occurrence] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.BatchCreateOccurrencesResponse: + r"""Creates new occurrences in batch. + + Args: + request (:class:`grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest`): + The request object. Request to create occurrences in + batch. + parent (:class:`str`): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrences + are to be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrences (:class:`Sequence[grafeas.grafeas_v1.types.Occurrence]`): + The occurrences to create. Max + allowed length is 1000. + + This corresponds to the ``occurrences`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse: + Response for creating occurrences in + batch. + + """ + # 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, occurrences]) + if request is 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 = grafeas.BatchCreateOccurrencesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if occurrences: + request.occurrences.extend(occurrences) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_create_occurrences, + default_timeout=30.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, + ) + + # Done; return the response. + return response + + async def update_occurrence(self, + request: grafeas.UpdateOccurrenceRequest = None, + *, + name: str = None, + occurrence: grafeas.Occurrence = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.Occurrence: + r"""Updates the specified occurrence. + + Args: + request (:class:`grafeas.grafeas_v1.types.UpdateOccurrenceRequest`): + The request object. Request to update an occurrence. + name (:class:`str`): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrence (:class:`grafeas.grafeas_v1.types.Occurrence`): + The updated occurrence. + This corresponds to the ``occurrence`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The fields 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: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + # 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, occurrence, 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 = grafeas.UpdateOccurrenceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if occurrence is not None: + request.occurrence = occurrence + 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_occurrence, + default_timeout=30.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 get_occurrence_note(self, + request: grafeas.GetOccurrenceNoteRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.Note: + r"""Gets the note attached to the specified occurrence. + Consumer projects can use this method to get a note that + belongs to a provider project. + + Args: + request (:class:`grafeas.grafeas_v1.types.GetOccurrenceNoteRequest`): + The request object. Request to get the note to which the + specified occurrence is attached. + name (:class:`str`): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a resource. + + """ + # 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 = grafeas.GetOccurrenceNoteRequest(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_occurrence_note, + 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=30.0, + ), + default_timeout=30.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 get_note(self, + request: grafeas.GetNoteRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.Note: + r"""Gets the specified note. + + Args: + request (:class:`grafeas.grafeas_v1.types.GetNoteRequest`): + The request object. Request to get a note. + name (:class:`str`): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a resource. + + """ + # 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 = grafeas.GetNoteRequest(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_note, + 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=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_notes(self, + request: grafeas.ListNotesRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNotesAsyncPager: + r"""Lists notes for the specified project. + + Args: + request (:class:`grafeas.grafeas_v1.types.ListNotesRequest`): + The request object. Request to list notes. + parent (:class:`str`): + The name of the project to list notes for in the form of + ``projects/[PROJECT_ID]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + The filter expression. + 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: + grafeas.grafeas_v1.services.grafeas.pagers.ListNotesAsyncPager: + Response for listing notes. + 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, 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 = grafeas.ListNotesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + 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_notes, + 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=30.0, + ), + default_timeout=30.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.ListNotesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_note(self, + request: grafeas.DeleteNoteRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified note. + + Args: + request (:class:`grafeas.grafeas_v1.types.DeleteNoteRequest`): + The request object. Request to delete a note. + name (:class:`str`): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # 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 = grafeas.DeleteNoteRequest(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_note, + 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=30.0, + ), + default_timeout=30.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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_note(self, + request: grafeas.CreateNoteRequest = None, + *, + parent: str = None, + note_id: str = None, + note: grafeas.Note = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.Note: + r"""Creates a new note. + + Args: + request (:class:`grafeas.grafeas_v1.types.CreateNoteRequest`): + The request object. Request to create a new note. + parent (:class:`str`): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the note is to be + created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note_id (:class:`str`): + The ID to use for this note. + This corresponds to the ``note_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note (:class:`grafeas.grafeas_v1.types.Note`): + The note to create. + This corresponds to the ``note`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a resource. + + """ + # 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, note_id, note]) + if request is 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 = grafeas.CreateNoteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if note_id is not None: + request.note_id = note_id + if note is not None: + request.note = note + + # 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_note, + default_timeout=30.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, + ) + + # Done; return the response. + return response + + async def batch_create_notes(self, + request: grafeas.BatchCreateNotesRequest = None, + *, + parent: str = None, + notes: Sequence[grafeas.BatchCreateNotesRequest.NotesEntry] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.BatchCreateNotesResponse: + r"""Creates new notes in batch. + + Args: + request (:class:`grafeas.grafeas_v1.types.BatchCreateNotesRequest`): + The request object. Request to create notes in batch. + parent (:class:`str`): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the notes are to + be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notes (:class:`Sequence[grafeas.grafeas_v1.types.BatchCreateNotesRequest.NotesEntry]`): + The notes to create. Max allowed + length is 1000. + + This corresponds to the ``notes`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + grafeas.grafeas_v1.types.BatchCreateNotesResponse: + Response for creating notes in batch. + """ + # 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, notes]) + if request is 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 = grafeas.BatchCreateNotesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + if notes: + request.notes.update(notes) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_create_notes, + default_timeout=30.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, + ) + + # Done; return the response. + return response + + async def update_note(self, + request: grafeas.UpdateNoteRequest = None, + *, + name: str = None, + note: grafeas.Note = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.Note: + r"""Updates the specified note. + + Args: + request (:class:`grafeas.grafeas_v1.types.UpdateNoteRequest`): + The request object. Request to update a note. + name (:class:`str`): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note (:class:`grafeas.grafeas_v1.types.Note`): + The updated note. + This corresponds to the ``note`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The fields 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: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a resource. + + """ + # 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, note, 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 = grafeas.UpdateNoteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if note is not None: + request.note = note + 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_note, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_note_occurrences(self, + request: grafeas.ListNoteOccurrencesRequest = None, + *, + name: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNoteOccurrencesAsyncPager: + r"""Lists occurrences referencing the specified note. + Provider projects can use this method to get all + occurrences across consumer projects referencing the + specified note. + + Args: + request (:class:`grafeas.grafeas_v1.types.ListNoteOccurrencesRequest`): + The request object. Request to list occurrences for a + note. + name (:class:`str`): + The name of the note to list occurrences for in the form + of ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + The filter expression. + 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: + grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesAsyncPager: + Response for listing occurrences for + a note. + 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([name, 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 = grafeas.ListNoteOccurrencesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + 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_note_occurrences, + 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=30.0, + ), + default_timeout=30.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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListNoteOccurrencesAsyncPager( + 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( + "grafeas-grafeas", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "GrafeasAsyncClient", +) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/client.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/client.py new file mode 100644 index 0000000..580eb34 --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/client.py @@ -0,0 +1,1567 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from grafeas.grafeas_v1.services.grafeas import pagers +from grafeas.grafeas_v1.types import attestation +from grafeas.grafeas_v1.types import build +from grafeas.grafeas_v1.types import common +from grafeas.grafeas_v1.types import deployment +from grafeas.grafeas_v1.types import discovery +from grafeas.grafeas_v1.types import grafeas +from grafeas.grafeas_v1.types import image +from grafeas.grafeas_v1.types import package +from grafeas.grafeas_v1.types import upgrade +from grafeas.grafeas_v1.types import vulnerability +from .transports.base import GrafeasTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import GrafeasGrpcTransport +from .transports.grpc_asyncio import GrafeasGrpcAsyncIOTransport + + +class GrafeasClientMeta(type): + """Metaclass for the Grafeas 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[GrafeasTransport]] + _transport_registry["grpc"] = GrafeasGrpcTransport + _transport_registry["grpc_asyncio"] = GrafeasGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[GrafeasTransport]: + """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 GrafeasClient(metaclass=GrafeasClientMeta): + """`Grafeas `__ API. + + Retrieves analysis results of Cloud components such as Docker + container images. + + Analysis results are stored as a series of occurrences. An + ``Occurrence`` contains information about a specific analysis + instance on a resource. An occurrence refers to a ``Note``. A note + contains details describing the analysis and is generally stored in + a separate project, called a ``Provider``. Multiple occurrences can + refer to the same note. + + For example, an SSL vulnerability could affect multiple images. In + this case, there would be one note for the vulnerability and an + occurrence for each image with the vulnerability referring to that + note. + """ + + @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 = "containeranalysis.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: + GrafeasClient: 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: + GrafeasClient: 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) -> GrafeasTransport: + """Returns the transport used by the client instance. + + Returns: + GrafeasTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def note_path(project: str,note: str,) -> str: + """Returns a fully-qualified note string.""" + return "projects/{project}/notes/{note}".format(project=project, note=note, ) + + @staticmethod + def parse_note_path(path: str) -> Dict[str,str]: + """Parses a note path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/notes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def occurrence_path(project: str,occurrence: str,) -> str: + """Returns a fully-qualified occurrence string.""" + return "projects/{project}/occurrences/{occurrence}".format(project=project, occurrence=occurrence, ) + + @staticmethod + def parse_occurrence_path(path: str) -> Dict[str,str]: + """Parses a occurrence path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/occurrences/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def project_path(project: str,) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_project_path(path: str) -> Dict[str,str]: + """Parses a project path into its component segments.""" + m = re.match(r"^projects/(?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, GrafeasTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the grafeas 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, GrafeasTransport]): 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, GrafeasTransport): + # transport is a GrafeasTransport 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 get_occurrence(self, + request: grafeas.GetOccurrenceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.Occurrence: + r"""Gets the specified occurrence. + + Args: + request (grafeas.grafeas_v1.types.GetOccurrenceRequest): + The request object. Request to get an occurrence. + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + # 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 grafeas.GetOccurrenceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, grafeas.GetOccurrenceRequest): + request = grafeas.GetOccurrenceRequest(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_occurrence] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_occurrences(self, + request: grafeas.ListOccurrencesRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListOccurrencesPager: + r"""Lists occurrences for the specified project. + + Args: + request (grafeas.grafeas_v1.types.ListOccurrencesRequest): + The request object. Request to list occurrences. + parent (str): + The name of the project to list occurrences for in the + form of ``projects/[PROJECT_ID]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + The filter expression. + 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: + grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesPager: + Response for listing occurrences. + 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, 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 grafeas.ListOccurrencesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, grafeas.ListOccurrencesRequest): + request = grafeas.ListOccurrencesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + 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_occurrences] + + # 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.ListOccurrencesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_occurrence(self, + request: grafeas.DeleteOccurrenceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified occurrence. For example, use + this method to delete an occurrence when the occurrence + is no longer applicable for the given resource. + + Args: + request (grafeas.grafeas_v1.types.DeleteOccurrenceRequest): + The request object. Request to delete an occurrence. + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # 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 grafeas.DeleteOccurrenceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, grafeas.DeleteOccurrenceRequest): + request = grafeas.DeleteOccurrenceRequest(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_occurrence] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_occurrence(self, + request: grafeas.CreateOccurrenceRequest = None, + *, + parent: str = None, + occurrence: grafeas.Occurrence = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.Occurrence: + r"""Creates a new occurrence. + + Args: + request (grafeas.grafeas_v1.types.CreateOccurrenceRequest): + The request object. Request to create a new occurrence. + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrence is + to be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrence (grafeas.grafeas_v1.types.Occurrence): + The occurrence to create. + This corresponds to the ``occurrence`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + # 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, occurrence]) + if request is 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 grafeas.CreateOccurrenceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, grafeas.CreateOccurrenceRequest): + request = grafeas.CreateOccurrenceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if occurrence is not None: + request.occurrence = occurrence + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_occurrence] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_create_occurrences(self, + request: grafeas.BatchCreateOccurrencesRequest = None, + *, + parent: str = None, + occurrences: Sequence[grafeas.Occurrence] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.BatchCreateOccurrencesResponse: + r"""Creates new occurrences in batch. + + Args: + request (grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest): + The request object. Request to create occurrences in + batch. + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrences + are to be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrences (Sequence[grafeas.grafeas_v1.types.Occurrence]): + The occurrences to create. Max + allowed length is 1000. + + This corresponds to the ``occurrences`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse: + Response for creating occurrences in + batch. + + """ + # 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, occurrences]) + if request is 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 grafeas.BatchCreateOccurrencesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, grafeas.BatchCreateOccurrencesRequest): + request = grafeas.BatchCreateOccurrencesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if occurrences is not None: + request.occurrences = occurrences + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_occurrences] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_occurrence(self, + request: grafeas.UpdateOccurrenceRequest = None, + *, + name: str = None, + occurrence: grafeas.Occurrence = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.Occurrence: + r"""Updates the specified occurrence. + + Args: + request (grafeas.grafeas_v1.types.UpdateOccurrenceRequest): + The request object. Request to update an occurrence. + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrence (grafeas.grafeas_v1.types.Occurrence): + The updated occurrence. + This corresponds to the ``occurrence`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields 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: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + # 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, occurrence, 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 grafeas.UpdateOccurrenceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, grafeas.UpdateOccurrenceRequest): + request = grafeas.UpdateOccurrenceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if occurrence is not None: + request.occurrence = occurrence + 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_occurrence] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_occurrence_note(self, + request: grafeas.GetOccurrenceNoteRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.Note: + r"""Gets the note attached to the specified occurrence. + Consumer projects can use this method to get a note that + belongs to a provider project. + + Args: + request (grafeas.grafeas_v1.types.GetOccurrenceNoteRequest): + The request object. Request to get the note to which the + specified occurrence is attached. + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a resource. + + """ + # 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 grafeas.GetOccurrenceNoteRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, grafeas.GetOccurrenceNoteRequest): + request = grafeas.GetOccurrenceNoteRequest(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_occurrence_note] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_note(self, + request: grafeas.GetNoteRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.Note: + r"""Gets the specified note. + + Args: + request (grafeas.grafeas_v1.types.GetNoteRequest): + The request object. Request to get a note. + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a resource. + + """ + # 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 grafeas.GetNoteRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, grafeas.GetNoteRequest): + request = grafeas.GetNoteRequest(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_note] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_notes(self, + request: grafeas.ListNotesRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNotesPager: + r"""Lists notes for the specified project. + + Args: + request (grafeas.grafeas_v1.types.ListNotesRequest): + The request object. Request to list notes. + parent (str): + The name of the project to list notes for in the form of + ``projects/[PROJECT_ID]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + The filter expression. + 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: + grafeas.grafeas_v1.services.grafeas.pagers.ListNotesPager: + Response for listing notes. + 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, 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 grafeas.ListNotesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, grafeas.ListNotesRequest): + request = grafeas.ListNotesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + 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_notes] + + # 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.ListNotesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_note(self, + request: grafeas.DeleteNoteRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified note. + + Args: + request (grafeas.grafeas_v1.types.DeleteNoteRequest): + The request object. Request to delete a note. + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # 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 grafeas.DeleteNoteRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, grafeas.DeleteNoteRequest): + request = grafeas.DeleteNoteRequest(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_note] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_note(self, + request: grafeas.CreateNoteRequest = None, + *, + parent: str = None, + note_id: str = None, + note: grafeas.Note = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.Note: + r"""Creates a new note. + + Args: + request (grafeas.grafeas_v1.types.CreateNoteRequest): + The request object. Request to create a new note. + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the note is to be + created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note_id (str): + The ID to use for this note. + This corresponds to the ``note_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note (grafeas.grafeas_v1.types.Note): + The note to create. + This corresponds to the ``note`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a resource. + + """ + # 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, note_id, note]) + if request is 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 grafeas.CreateNoteRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, grafeas.CreateNoteRequest): + request = grafeas.CreateNoteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if note_id is not None: + request.note_id = note_id + if note is not None: + request.note = note + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_note] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_create_notes(self, + request: grafeas.BatchCreateNotesRequest = None, + *, + parent: str = None, + notes: Sequence[grafeas.BatchCreateNotesRequest.NotesEntry] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.BatchCreateNotesResponse: + r"""Creates new notes in batch. + + Args: + request (grafeas.grafeas_v1.types.BatchCreateNotesRequest): + The request object. Request to create notes in batch. + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the notes are to + be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notes (Sequence[grafeas.grafeas_v1.types.BatchCreateNotesRequest.NotesEntry]): + The notes to create. Max allowed + length is 1000. + + This corresponds to the ``notes`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + grafeas.grafeas_v1.types.BatchCreateNotesResponse: + Response for creating notes in batch. + """ + # 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, notes]) + if request is 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 grafeas.BatchCreateNotesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, grafeas.BatchCreateNotesRequest): + request = grafeas.BatchCreateNotesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if notes is not None: + request.notes = notes + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_notes] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_note(self, + request: grafeas.UpdateNoteRequest = None, + *, + name: str = None, + note: grafeas.Note = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grafeas.Note: + r"""Updates the specified note. + + Args: + request (grafeas.grafeas_v1.types.UpdateNoteRequest): + The request object. Request to update a note. + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note (grafeas.grafeas_v1.types.Note): + The updated note. + This corresponds to the ``note`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields 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: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a resource. + + """ + # 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, note, 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 grafeas.UpdateNoteRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, grafeas.UpdateNoteRequest): + request = grafeas.UpdateNoteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if note is not None: + request.note = note + 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_note] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_note_occurrences(self, + request: grafeas.ListNoteOccurrencesRequest = None, + *, + name: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNoteOccurrencesPager: + r"""Lists occurrences referencing the specified note. + Provider projects can use this method to get all + occurrences across consumer projects referencing the + specified note. + + Args: + request (grafeas.grafeas_v1.types.ListNoteOccurrencesRequest): + The request object. Request to list occurrences for a + note. + name (str): + The name of the note to list occurrences for in the form + of ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + The filter expression. + 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: + grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesPager: + Response for listing occurrences for + a note. + 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([name, 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 grafeas.ListNoteOccurrencesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, grafeas.ListNoteOccurrencesRequest): + request = grafeas.ListNoteOccurrencesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + 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_note_occurrences] + + # 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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListNoteOccurrencesPager( + 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( + "grafeas-grafeas", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "GrafeasClient", +) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/pagers.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/pagers.py new file mode 100644 index 0000000..de16137 --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/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 grafeas.grafeas_v1.types import grafeas + + +class ListOccurrencesPager: + """A pager for iterating through ``list_occurrences`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``occurrences`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListOccurrences`` requests and continue to iterate + through the ``occurrences`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` + 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[..., grafeas.ListOccurrencesResponse], + request: grafeas.ListOccurrencesRequest, + response: grafeas.ListOccurrencesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (grafeas.grafeas_v1.types.ListOccurrencesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListOccurrencesResponse): + 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 = grafeas.ListOccurrencesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[grafeas.ListOccurrencesResponse]: + 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[grafeas.Occurrence]: + for page in self.pages: + yield from page.occurrences + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListOccurrencesAsyncPager: + """A pager for iterating through ``list_occurrences`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``occurrences`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListOccurrences`` requests and continue to iterate + through the ``occurrences`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` + 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[grafeas.ListOccurrencesResponse]], + request: grafeas.ListOccurrencesRequest, + response: grafeas.ListOccurrencesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (grafeas.grafeas_v1.types.ListOccurrencesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListOccurrencesResponse): + 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 = grafeas.ListOccurrencesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[grafeas.ListOccurrencesResponse]: + 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[grafeas.Occurrence]: + async def async_generator(): + async for page in self.pages: + for response in page.occurrences: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotesPager: + """A pager for iterating through ``list_notes`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListNotesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``notes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNotes`` requests and continue to iterate + through the ``notes`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListNotesResponse` + 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[..., grafeas.ListNotesResponse], + request: grafeas.ListNotesRequest, + response: grafeas.ListNotesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (grafeas.grafeas_v1.types.ListNotesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListNotesResponse): + 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 = grafeas.ListNotesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[grafeas.ListNotesResponse]: + 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[grafeas.Note]: + for page in self.pages: + yield from page.notes + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotesAsyncPager: + """A pager for iterating through ``list_notes`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListNotesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``notes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNotes`` requests and continue to iterate + through the ``notes`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListNotesResponse` + 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[grafeas.ListNotesResponse]], + request: grafeas.ListNotesRequest, + response: grafeas.ListNotesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (grafeas.grafeas_v1.types.ListNotesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListNotesResponse): + 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 = grafeas.ListNotesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[grafeas.ListNotesResponse]: + 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[grafeas.Note]: + async def async_generator(): + async for page in self.pages: + for response in page.notes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNoteOccurrencesPager: + """A pager for iterating through ``list_note_occurrences`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``occurrences`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNoteOccurrences`` requests and continue to iterate + through the ``occurrences`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` + 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[..., grafeas.ListNoteOccurrencesResponse], + request: grafeas.ListNoteOccurrencesRequest, + response: grafeas.ListNoteOccurrencesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (grafeas.grafeas_v1.types.ListNoteOccurrencesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListNoteOccurrencesResponse): + 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 = grafeas.ListNoteOccurrencesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[grafeas.ListNoteOccurrencesResponse]: + 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[grafeas.Occurrence]: + for page in self.pages: + yield from page.occurrences + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNoteOccurrencesAsyncPager: + """A pager for iterating through ``list_note_occurrences`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``occurrences`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNoteOccurrences`` requests and continue to iterate + through the ``occurrences`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` + 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[grafeas.ListNoteOccurrencesResponse]], + request: grafeas.ListNoteOccurrencesRequest, + response: grafeas.ListNoteOccurrencesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (grafeas.grafeas_v1.types.ListNoteOccurrencesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListNoteOccurrencesResponse): + 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 = grafeas.ListNoteOccurrencesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[grafeas.ListNoteOccurrencesResponse]: + 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[grafeas.Occurrence]: + async def async_generator(): + async for page in self.pages: + for response in page.occurrences: + 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/grafeas/grafeas_v1/services/grafeas/transports/__init__.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/__init__.py new file mode 100644 index 0000000..d042d7b --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/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 GrafeasTransport +from .grpc import GrafeasGrpcTransport +from .grpc_asyncio import GrafeasGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[GrafeasTransport]] +_transport_registry['grpc'] = GrafeasGrpcTransport +_transport_registry['grpc_asyncio'] = GrafeasGrpcAsyncIOTransport + +__all__ = ( + 'GrafeasTransport', + 'GrafeasGrpcTransport', + 'GrafeasGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/base.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/base.py new file mode 100644 index 0000000..ca7979d --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/base.py @@ -0,0 +1,406 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.protobuf import empty_pb2 # type: ignore +from grafeas.grafeas_v1.types import grafeas + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'grafeas-grafeas', + ).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 GrafeasTransport(abc.ABC): + """Abstract transport class for Grafeas.""" + + AUTH_SCOPES = ( + ) + + DEFAULT_HOST: str = 'containeranalysis.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.get_occurrence: gapic_v1.method.wrap_method( + self.get_occurrence, + 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=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_occurrences: gapic_v1.method.wrap_method( + self.list_occurrences, + 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=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_occurrence: gapic_v1.method.wrap_method( + self.delete_occurrence, + 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=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_occurrence: gapic_v1.method.wrap_method( + self.create_occurrence, + default_timeout=30.0, + client_info=client_info, + ), + self.batch_create_occurrences: gapic_v1.method.wrap_method( + self.batch_create_occurrences, + default_timeout=30.0, + client_info=client_info, + ), + self.update_occurrence: gapic_v1.method.wrap_method( + self.update_occurrence, + default_timeout=30.0, + client_info=client_info, + ), + self.get_occurrence_note: gapic_v1.method.wrap_method( + self.get_occurrence_note, + 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=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_note: gapic_v1.method.wrap_method( + self.get_note, + 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=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_notes: gapic_v1.method.wrap_method( + self.list_notes, + 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=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_note: gapic_v1.method.wrap_method( + self.delete_note, + 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=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_note: gapic_v1.method.wrap_method( + self.create_note, + default_timeout=30.0, + client_info=client_info, + ), + self.batch_create_notes: gapic_v1.method.wrap_method( + self.batch_create_notes, + default_timeout=30.0, + client_info=client_info, + ), + self.update_note: gapic_v1.method.wrap_method( + self.update_note, + default_timeout=30.0, + client_info=client_info, + ), + self.list_note_occurrences: gapic_v1.method.wrap_method( + self.list_note_occurrences, + 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=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + } + + @property + def get_occurrence(self) -> Callable[ + [grafeas.GetOccurrenceRequest], + Union[ + grafeas.Occurrence, + Awaitable[grafeas.Occurrence] + ]]: + raise NotImplementedError() + + @property + def list_occurrences(self) -> Callable[ + [grafeas.ListOccurrencesRequest], + Union[ + grafeas.ListOccurrencesResponse, + Awaitable[grafeas.ListOccurrencesResponse] + ]]: + raise NotImplementedError() + + @property + def delete_occurrence(self) -> Callable[ + [grafeas.DeleteOccurrenceRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_occurrence(self) -> Callable[ + [grafeas.CreateOccurrenceRequest], + Union[ + grafeas.Occurrence, + Awaitable[grafeas.Occurrence] + ]]: + raise NotImplementedError() + + @property + def batch_create_occurrences(self) -> Callable[ + [grafeas.BatchCreateOccurrencesRequest], + Union[ + grafeas.BatchCreateOccurrencesResponse, + Awaitable[grafeas.BatchCreateOccurrencesResponse] + ]]: + raise NotImplementedError() + + @property + def update_occurrence(self) -> Callable[ + [grafeas.UpdateOccurrenceRequest], + Union[ + grafeas.Occurrence, + Awaitable[grafeas.Occurrence] + ]]: + raise NotImplementedError() + + @property + def get_occurrence_note(self) -> Callable[ + [grafeas.GetOccurrenceNoteRequest], + Union[ + grafeas.Note, + Awaitable[grafeas.Note] + ]]: + raise NotImplementedError() + + @property + def get_note(self) -> Callable[ + [grafeas.GetNoteRequest], + Union[ + grafeas.Note, + Awaitable[grafeas.Note] + ]]: + raise NotImplementedError() + + @property + def list_notes(self) -> Callable[ + [grafeas.ListNotesRequest], + Union[ + grafeas.ListNotesResponse, + Awaitable[grafeas.ListNotesResponse] + ]]: + raise NotImplementedError() + + @property + def delete_note(self) -> Callable[ + [grafeas.DeleteNoteRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_note(self) -> Callable[ + [grafeas.CreateNoteRequest], + Union[ + grafeas.Note, + Awaitable[grafeas.Note] + ]]: + raise NotImplementedError() + + @property + def batch_create_notes(self) -> Callable[ + [grafeas.BatchCreateNotesRequest], + Union[ + grafeas.BatchCreateNotesResponse, + Awaitable[grafeas.BatchCreateNotesResponse] + ]]: + raise NotImplementedError() + + @property + def update_note(self) -> Callable[ + [grafeas.UpdateNoteRequest], + Union[ + grafeas.Note, + Awaitable[grafeas.Note] + ]]: + raise NotImplementedError() + + @property + def list_note_occurrences(self) -> Callable[ + [grafeas.ListNoteOccurrencesRequest], + Union[ + grafeas.ListNoteOccurrencesResponse, + Awaitable[grafeas.ListNoteOccurrencesResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'GrafeasTransport', +) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc.py new file mode 100644 index 0000000..4972ab8 --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc.py @@ -0,0 +1,613 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.protobuf import empty_pb2 # type: ignore +from grafeas.grafeas_v1.types import grafeas +from .base import GrafeasTransport, DEFAULT_CLIENT_INFO + + +class GrafeasGrpcTransport(GrafeasTransport): + """gRPC backend transport for Grafeas. + + `Grafeas `__ API. + + Retrieves analysis results of Cloud components such as Docker + container images. + + Analysis results are stored as a series of occurrences. An + ``Occurrence`` contains information about a specific analysis + instance on a resource. An occurrence refers to a ``Note``. A note + contains details describing the analysis and is generally stored in + a separate project, called a ``Provider``. Multiple occurrences can + refer to the same note. + + For example, an SSL vulnerability could affect multiple images. In + this case, there would be one note for the vulnerability and an + occurrence for each image with the vulnerability referring to that + note. + + 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 = 'containeranalysis.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] = {} + + 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 = 'containeranalysis.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 get_occurrence(self) -> Callable[ + [grafeas.GetOccurrenceRequest], + grafeas.Occurrence]: + r"""Return a callable for the get occurrence method over gRPC. + + Gets the specified occurrence. + + Returns: + Callable[[~.GetOccurrenceRequest], + ~.Occurrence]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrence' not in self._stubs: + self._stubs['get_occurrence'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/GetOccurrence', + request_serializer=grafeas.GetOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs['get_occurrence'] + + @property + def list_occurrences(self) -> Callable[ + [grafeas.ListOccurrencesRequest], + grafeas.ListOccurrencesResponse]: + r"""Return a callable for the list occurrences method over gRPC. + + Lists occurrences for the specified project. + + Returns: + Callable[[~.ListOccurrencesRequest], + ~.ListOccurrencesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrences' not in self._stubs: + self._stubs['list_occurrences'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/ListOccurrences', + request_serializer=grafeas.ListOccurrencesRequest.serialize, + response_deserializer=grafeas.ListOccurrencesResponse.deserialize, + ) + return self._stubs['list_occurrences'] + + @property + def delete_occurrence(self) -> Callable[ + [grafeas.DeleteOccurrenceRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete occurrence method over gRPC. + + Deletes the specified occurrence. For example, use + this method to delete an occurrence when the occurrence + is no longer applicable for the given resource. + + Returns: + Callable[[~.DeleteOccurrenceRequest], + ~.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_occurrence' not in self._stubs: + self._stubs['delete_occurrence'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/DeleteOccurrence', + request_serializer=grafeas.DeleteOccurrenceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_occurrence'] + + @property + def create_occurrence(self) -> Callable[ + [grafeas.CreateOccurrenceRequest], + grafeas.Occurrence]: + r"""Return a callable for the create occurrence method over gRPC. + + Creates a new occurrence. + + Returns: + Callable[[~.CreateOccurrenceRequest], + ~.Occurrence]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrence' not in self._stubs: + self._stubs['create_occurrence'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/CreateOccurrence', + request_serializer=grafeas.CreateOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs['create_occurrence'] + + @property + def batch_create_occurrences(self) -> Callable[ + [grafeas.BatchCreateOccurrencesRequest], + grafeas.BatchCreateOccurrencesResponse]: + r"""Return a callable for the batch create occurrences method over gRPC. + + Creates new occurrences in batch. + + Returns: + Callable[[~.BatchCreateOccurrencesRequest], + ~.BatchCreateOccurrencesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_create_occurrences' not in self._stubs: + self._stubs['batch_create_occurrences'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/BatchCreateOccurrences', + request_serializer=grafeas.BatchCreateOccurrencesRequest.serialize, + response_deserializer=grafeas.BatchCreateOccurrencesResponse.deserialize, + ) + return self._stubs['batch_create_occurrences'] + + @property + def update_occurrence(self) -> Callable[ + [grafeas.UpdateOccurrenceRequest], + grafeas.Occurrence]: + r"""Return a callable for the update occurrence method over gRPC. + + Updates the specified occurrence. + + Returns: + Callable[[~.UpdateOccurrenceRequest], + ~.Occurrence]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrence' not in self._stubs: + self._stubs['update_occurrence'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/UpdateOccurrence', + request_serializer=grafeas.UpdateOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs['update_occurrence'] + + @property + def get_occurrence_note(self) -> Callable[ + [grafeas.GetOccurrenceNoteRequest], + grafeas.Note]: + r"""Return a callable for the get occurrence note method over gRPC. + + Gets the note attached to the specified occurrence. + Consumer projects can use this method to get a note that + belongs to a provider project. + + Returns: + Callable[[~.GetOccurrenceNoteRequest], + ~.Note]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrence_note' not in self._stubs: + self._stubs['get_occurrence_note'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/GetOccurrenceNote', + request_serializer=grafeas.GetOccurrenceNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs['get_occurrence_note'] + + @property + def get_note(self) -> Callable[ + [grafeas.GetNoteRequest], + grafeas.Note]: + r"""Return a callable for the get note method over gRPC. + + Gets the specified note. + + Returns: + Callable[[~.GetNoteRequest], + ~.Note]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_note' not in self._stubs: + self._stubs['get_note'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/GetNote', + request_serializer=grafeas.GetNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs['get_note'] + + @property + def list_notes(self) -> Callable[ + [grafeas.ListNotesRequest], + grafeas.ListNotesResponse]: + r"""Return a callable for the list notes method over gRPC. + + Lists notes for the specified project. + + Returns: + Callable[[~.ListNotesRequest], + ~.ListNotesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notes' not in self._stubs: + self._stubs['list_notes'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/ListNotes', + request_serializer=grafeas.ListNotesRequest.serialize, + response_deserializer=grafeas.ListNotesResponse.deserialize, + ) + return self._stubs['list_notes'] + + @property + def delete_note(self) -> Callable[ + [grafeas.DeleteNoteRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete note method over gRPC. + + Deletes the specified note. + + Returns: + Callable[[~.DeleteNoteRequest], + ~.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_note' not in self._stubs: + self._stubs['delete_note'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/DeleteNote', + request_serializer=grafeas.DeleteNoteRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_note'] + + @property + def create_note(self) -> Callable[ + [grafeas.CreateNoteRequest], + grafeas.Note]: + r"""Return a callable for the create note method over gRPC. + + Creates a new note. + + Returns: + Callable[[~.CreateNoteRequest], + ~.Note]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_note' not in self._stubs: + self._stubs['create_note'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/CreateNote', + request_serializer=grafeas.CreateNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs['create_note'] + + @property + def batch_create_notes(self) -> Callable[ + [grafeas.BatchCreateNotesRequest], + grafeas.BatchCreateNotesResponse]: + r"""Return a callable for the batch create notes method over gRPC. + + Creates new notes in batch. + + Returns: + Callable[[~.BatchCreateNotesRequest], + ~.BatchCreateNotesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_create_notes' not in self._stubs: + self._stubs['batch_create_notes'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/BatchCreateNotes', + request_serializer=grafeas.BatchCreateNotesRequest.serialize, + response_deserializer=grafeas.BatchCreateNotesResponse.deserialize, + ) + return self._stubs['batch_create_notes'] + + @property + def update_note(self) -> Callable[ + [grafeas.UpdateNoteRequest], + grafeas.Note]: + r"""Return a callable for the update note method over gRPC. + + Updates the specified note. + + Returns: + Callable[[~.UpdateNoteRequest], + ~.Note]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_note' not in self._stubs: + self._stubs['update_note'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/UpdateNote', + request_serializer=grafeas.UpdateNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs['update_note'] + + @property + def list_note_occurrences(self) -> Callable[ + [grafeas.ListNoteOccurrencesRequest], + grafeas.ListNoteOccurrencesResponse]: + r"""Return a callable for the list note occurrences method over gRPC. + + Lists occurrences referencing the specified note. + Provider projects can use this method to get all + occurrences across consumer projects referencing the + specified note. + + Returns: + Callable[[~.ListNoteOccurrencesRequest], + ~.ListNoteOccurrencesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_note_occurrences' not in self._stubs: + self._stubs['list_note_occurrences'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/ListNoteOccurrences', + request_serializer=grafeas.ListNoteOccurrencesRequest.serialize, + response_deserializer=grafeas.ListNoteOccurrencesResponse.deserialize, + ) + return self._stubs['list_note_occurrences'] + + +__all__ = ( + 'GrafeasGrpcTransport', +) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py new file mode 100644 index 0000000..623e8ee --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py @@ -0,0 +1,617 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.protobuf import empty_pb2 # type: ignore +from grafeas.grafeas_v1.types import grafeas +from .base import GrafeasTransport, DEFAULT_CLIENT_INFO +from .grpc import GrafeasGrpcTransport + + +class GrafeasGrpcAsyncIOTransport(GrafeasTransport): + """gRPC AsyncIO backend transport for Grafeas. + + `Grafeas `__ API. + + Retrieves analysis results of Cloud components such as Docker + container images. + + Analysis results are stored as a series of occurrences. An + ``Occurrence`` contains information about a specific analysis + instance on a resource. An occurrence refers to a ``Note``. A note + contains details describing the analysis and is generally stored in + a separate project, called a ``Provider``. Multiple occurrences can + refer to the same note. + + For example, an SSL vulnerability could affect multiple images. In + this case, there would be one note for the vulnerability and an + occurrence for each image with the vulnerability referring to that + note. + + 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 = 'containeranalysis.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 = 'containeranalysis.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] = {} + + 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 get_occurrence(self) -> Callable[ + [grafeas.GetOccurrenceRequest], + Awaitable[grafeas.Occurrence]]: + r"""Return a callable for the get occurrence method over gRPC. + + Gets the specified occurrence. + + Returns: + Callable[[~.GetOccurrenceRequest], + Awaitable[~.Occurrence]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrence' not in self._stubs: + self._stubs['get_occurrence'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/GetOccurrence', + request_serializer=grafeas.GetOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs['get_occurrence'] + + @property + def list_occurrences(self) -> Callable[ + [grafeas.ListOccurrencesRequest], + Awaitable[grafeas.ListOccurrencesResponse]]: + r"""Return a callable for the list occurrences method over gRPC. + + Lists occurrences for the specified project. + + Returns: + Callable[[~.ListOccurrencesRequest], + Awaitable[~.ListOccurrencesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrences' not in self._stubs: + self._stubs['list_occurrences'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/ListOccurrences', + request_serializer=grafeas.ListOccurrencesRequest.serialize, + response_deserializer=grafeas.ListOccurrencesResponse.deserialize, + ) + return self._stubs['list_occurrences'] + + @property + def delete_occurrence(self) -> Callable[ + [grafeas.DeleteOccurrenceRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete occurrence method over gRPC. + + Deletes the specified occurrence. For example, use + this method to delete an occurrence when the occurrence + is no longer applicable for the given resource. + + Returns: + Callable[[~.DeleteOccurrenceRequest], + 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_occurrence' not in self._stubs: + self._stubs['delete_occurrence'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/DeleteOccurrence', + request_serializer=grafeas.DeleteOccurrenceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_occurrence'] + + @property + def create_occurrence(self) -> Callable[ + [grafeas.CreateOccurrenceRequest], + Awaitable[grafeas.Occurrence]]: + r"""Return a callable for the create occurrence method over gRPC. + + Creates a new occurrence. + + Returns: + Callable[[~.CreateOccurrenceRequest], + Awaitable[~.Occurrence]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrence' not in self._stubs: + self._stubs['create_occurrence'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/CreateOccurrence', + request_serializer=grafeas.CreateOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs['create_occurrence'] + + @property + def batch_create_occurrences(self) -> Callable[ + [grafeas.BatchCreateOccurrencesRequest], + Awaitable[grafeas.BatchCreateOccurrencesResponse]]: + r"""Return a callable for the batch create occurrences method over gRPC. + + Creates new occurrences in batch. + + Returns: + Callable[[~.BatchCreateOccurrencesRequest], + Awaitable[~.BatchCreateOccurrencesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_create_occurrences' not in self._stubs: + self._stubs['batch_create_occurrences'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/BatchCreateOccurrences', + request_serializer=grafeas.BatchCreateOccurrencesRequest.serialize, + response_deserializer=grafeas.BatchCreateOccurrencesResponse.deserialize, + ) + return self._stubs['batch_create_occurrences'] + + @property + def update_occurrence(self) -> Callable[ + [grafeas.UpdateOccurrenceRequest], + Awaitable[grafeas.Occurrence]]: + r"""Return a callable for the update occurrence method over gRPC. + + Updates the specified occurrence. + + Returns: + Callable[[~.UpdateOccurrenceRequest], + Awaitable[~.Occurrence]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrence' not in self._stubs: + self._stubs['update_occurrence'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/UpdateOccurrence', + request_serializer=grafeas.UpdateOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs['update_occurrence'] + + @property + def get_occurrence_note(self) -> Callable[ + [grafeas.GetOccurrenceNoteRequest], + Awaitable[grafeas.Note]]: + r"""Return a callable for the get occurrence note method over gRPC. + + Gets the note attached to the specified occurrence. + Consumer projects can use this method to get a note that + belongs to a provider project. + + Returns: + Callable[[~.GetOccurrenceNoteRequest], + Awaitable[~.Note]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_occurrence_note' not in self._stubs: + self._stubs['get_occurrence_note'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/GetOccurrenceNote', + request_serializer=grafeas.GetOccurrenceNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs['get_occurrence_note'] + + @property + def get_note(self) -> Callable[ + [grafeas.GetNoteRequest], + Awaitable[grafeas.Note]]: + r"""Return a callable for the get note method over gRPC. + + Gets the specified note. + + Returns: + Callable[[~.GetNoteRequest], + Awaitable[~.Note]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_note' not in self._stubs: + self._stubs['get_note'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/GetNote', + request_serializer=grafeas.GetNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs['get_note'] + + @property + def list_notes(self) -> Callable[ + [grafeas.ListNotesRequest], + Awaitable[grafeas.ListNotesResponse]]: + r"""Return a callable for the list notes method over gRPC. + + Lists notes for the specified project. + + Returns: + Callable[[~.ListNotesRequest], + Awaitable[~.ListNotesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notes' not in self._stubs: + self._stubs['list_notes'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/ListNotes', + request_serializer=grafeas.ListNotesRequest.serialize, + response_deserializer=grafeas.ListNotesResponse.deserialize, + ) + return self._stubs['list_notes'] + + @property + def delete_note(self) -> Callable[ + [grafeas.DeleteNoteRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete note method over gRPC. + + Deletes the specified note. + + Returns: + Callable[[~.DeleteNoteRequest], + 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_note' not in self._stubs: + self._stubs['delete_note'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/DeleteNote', + request_serializer=grafeas.DeleteNoteRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_note'] + + @property + def create_note(self) -> Callable[ + [grafeas.CreateNoteRequest], + Awaitable[grafeas.Note]]: + r"""Return a callable for the create note method over gRPC. + + Creates a new note. + + Returns: + Callable[[~.CreateNoteRequest], + Awaitable[~.Note]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_note' not in self._stubs: + self._stubs['create_note'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/CreateNote', + request_serializer=grafeas.CreateNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs['create_note'] + + @property + def batch_create_notes(self) -> Callable[ + [grafeas.BatchCreateNotesRequest], + Awaitable[grafeas.BatchCreateNotesResponse]]: + r"""Return a callable for the batch create notes method over gRPC. + + Creates new notes in batch. + + Returns: + Callable[[~.BatchCreateNotesRequest], + Awaitable[~.BatchCreateNotesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_create_notes' not in self._stubs: + self._stubs['batch_create_notes'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/BatchCreateNotes', + request_serializer=grafeas.BatchCreateNotesRequest.serialize, + response_deserializer=grafeas.BatchCreateNotesResponse.deserialize, + ) + return self._stubs['batch_create_notes'] + + @property + def update_note(self) -> Callable[ + [grafeas.UpdateNoteRequest], + Awaitable[grafeas.Note]]: + r"""Return a callable for the update note method over gRPC. + + Updates the specified note. + + Returns: + Callable[[~.UpdateNoteRequest], + Awaitable[~.Note]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_note' not in self._stubs: + self._stubs['update_note'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/UpdateNote', + request_serializer=grafeas.UpdateNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs['update_note'] + + @property + def list_note_occurrences(self) -> Callable[ + [grafeas.ListNoteOccurrencesRequest], + Awaitable[grafeas.ListNoteOccurrencesResponse]]: + r"""Return a callable for the list note occurrences method over gRPC. + + Lists occurrences referencing the specified note. + Provider projects can use this method to get all + occurrences across consumer projects referencing the + specified note. + + Returns: + Callable[[~.ListNoteOccurrencesRequest], + Awaitable[~.ListNoteOccurrencesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_note_occurrences' not in self._stubs: + self._stubs['list_note_occurrences'] = self.grpc_channel.unary_unary( + '/grafeas.v1.Grafeas/ListNoteOccurrences', + request_serializer=grafeas.ListNoteOccurrencesRequest.serialize, + response_deserializer=grafeas.ListNoteOccurrencesResponse.deserialize, + ) + return self._stubs['list_note_occurrences'] + + +__all__ = ( + 'GrafeasGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/__init__.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/__init__.py new file mode 100644 index 0000000..e71985c --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/types/__init__.py @@ -0,0 +1,168 @@ +# -*- 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 .attestation import ( + AttestationNote, + AttestationOccurrence, +) +from .build import ( + BuildNote, + BuildOccurrence, +) +from .common import ( + RelatedUrl, + Signature, + NoteKind, +) +from .cvss import ( + CVSSv3, +) +from .deployment import ( + DeploymentNote, + DeploymentOccurrence, +) +from .discovery import ( + DiscoveryNote, + DiscoveryOccurrence, +) +from .grafeas import ( + BatchCreateNotesRequest, + BatchCreateNotesResponse, + BatchCreateOccurrencesRequest, + BatchCreateOccurrencesResponse, + CreateNoteRequest, + CreateOccurrenceRequest, + DeleteNoteRequest, + DeleteOccurrenceRequest, + GetNoteRequest, + GetOccurrenceNoteRequest, + GetOccurrenceRequest, + ListNoteOccurrencesRequest, + ListNoteOccurrencesResponse, + ListNotesRequest, + ListNotesResponse, + ListOccurrencesRequest, + ListOccurrencesResponse, + Note, + Occurrence, + UpdateNoteRequest, + UpdateOccurrenceRequest, +) +from .image import ( + Fingerprint, + ImageNote, + ImageOccurrence, + Layer, +) +from .package import ( + Distribution, + Location, + PackageNote, + PackageOccurrence, + Version, + Architecture, +) +from .provenance import ( + AliasContext, + Artifact, + BuildProvenance, + CloudRepoSourceContext, + Command, + FileHashes, + GerritSourceContext, + GitSourceContext, + Hash, + ProjectRepoId, + RepoId, + Source, + SourceContext, +) +from .upgrade import ( + UpgradeDistribution, + UpgradeNote, + UpgradeOccurrence, + WindowsUpdate, +) +from .vulnerability import ( + VulnerabilityNote, + VulnerabilityOccurrence, + Severity, +) + +__all__ = ( + 'AttestationNote', + 'AttestationOccurrence', + 'BuildNote', + 'BuildOccurrence', + 'RelatedUrl', + 'Signature', + 'NoteKind', + 'CVSSv3', + 'DeploymentNote', + 'DeploymentOccurrence', + 'DiscoveryNote', + 'DiscoveryOccurrence', + 'BatchCreateNotesRequest', + 'BatchCreateNotesResponse', + 'BatchCreateOccurrencesRequest', + 'BatchCreateOccurrencesResponse', + 'CreateNoteRequest', + 'CreateOccurrenceRequest', + 'DeleteNoteRequest', + 'DeleteOccurrenceRequest', + 'GetNoteRequest', + 'GetOccurrenceNoteRequest', + 'GetOccurrenceRequest', + 'ListNoteOccurrencesRequest', + 'ListNoteOccurrencesResponse', + 'ListNotesRequest', + 'ListNotesResponse', + 'ListOccurrencesRequest', + 'ListOccurrencesResponse', + 'Note', + 'Occurrence', + 'UpdateNoteRequest', + 'UpdateOccurrenceRequest', + 'Fingerprint', + 'ImageNote', + 'ImageOccurrence', + 'Layer', + 'Distribution', + 'Location', + 'PackageNote', + 'PackageOccurrence', + 'Version', + 'Architecture', + 'AliasContext', + 'Artifact', + 'BuildProvenance', + 'CloudRepoSourceContext', + 'Command', + 'FileHashes', + 'GerritSourceContext', + 'GitSourceContext', + 'Hash', + 'ProjectRepoId', + 'RepoId', + 'Source', + 'SourceContext', + 'UpgradeDistribution', + 'UpgradeNote', + 'UpgradeOccurrence', + 'WindowsUpdate', + 'VulnerabilityNote', + 'VulnerabilityOccurrence', + 'Severity', +) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/attestation.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/attestation.py new file mode 100644 index 0000000..f91538d --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/types/attestation.py @@ -0,0 +1,109 @@ +# -*- 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 grafeas.grafeas_v1.types import common + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'AttestationNote', + 'AttestationOccurrence', + }, +) + + +class AttestationNote(proto.Message): + r"""Note kind that represents a logical attestation "role" or + "authority". For example, an organization might have one + ``Authority`` for "QA" and one for "build". This note is intended to + act strictly as a grouping mechanism for the attached occurrences + (Attestations). This grouping mechanism also provides a security + boundary, since IAM ACLs gate the ability for a principle to attach + an occurrence to a given note. It also provides a single point of + lookup to find all attached attestation occurrences, even if they + don't all live in the same project. + + Attributes: + hint (grafeas.grafeas_v1.types.AttestationNote.Hint): + Hint hints at the purpose of the attestation + authority. + """ + + class Hint(proto.Message): + r"""This submessage provides human-readable hints about the + purpose of the authority. Because the name of a note acts as its + resource reference, it is important to disambiguate the + canonical name of the Note (which might be a UUID for security + purposes) from "readable" names more suitable for debug output. + Note that these hints should not be used to look up authorities + in security sensitive contexts, such as when looking up + attestations to verify. + + Attributes: + human_readable_name (str): + Required. The human readable name of this + attestation authority, for example "qa". + """ + + human_readable_name = proto.Field( + proto.STRING, + number=1, + ) + + hint = proto.Field( + proto.MESSAGE, + number=1, + message=Hint, + ) + + +class AttestationOccurrence(proto.Message): + r"""Occurrence that represents a single "attestation". The + authenticity of an attestation can be verified using the + attached signature. If the verifier trusts the public key of the + signer, then verifying the signature is sufficient to establish + trust. In this circumstance, the authority to which this + attestation is attached is primarily useful for lookup (how to + find this attestation if you already know the authority and + artifact to be verified) and intent (for which authority this + attestation was intended to sign. + + Attributes: + serialized_payload (bytes): + Required. The serialized payload that is verified by one or + more ``signatures``. + signatures (Sequence[grafeas.grafeas_v1.types.Signature]): + One or more signatures over ``serialized_payload``. Verifier + implementations should consider this attestation message + verified if at least one ``signature`` verifies + ``serialized_payload``. See ``Signature`` in common.proto + for more details on signature structure and verification. + """ + + serialized_payload = proto.Field( + proto.BYTES, + number=1, + ) + signatures = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.Signature, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/build.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/build.py new file mode 100644 index 0000000..d01732f --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/types/build.py @@ -0,0 +1,79 @@ +# -*- 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 grafeas.grafeas_v1.types import provenance as g_provenance + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'BuildNote', + 'BuildOccurrence', + }, +) + + +class BuildNote(proto.Message): + r"""Note holding the version of the provider's builder and the + signature of the provenance message in the build details + occurrence. + + Attributes: + builder_version (str): + Required. Immutable. Version of the builder + which produced this build. + """ + + builder_version = proto.Field( + proto.STRING, + number=1, + ) + + +class BuildOccurrence(proto.Message): + r"""Details of a build occurrence. + Attributes: + provenance (grafeas.grafeas_v1.types.BuildProvenance): + Required. The actual provenance for the + build. + provenance_bytes (str): + Serialized JSON representation of the provenance, used in + generating the build signature in the corresponding build + note. After verifying the signature, ``provenance_bytes`` + can be unmarshalled and compared to the provenance to + confirm that it is unchanged. A base64-encoded string + representation of the provenance bytes is used for the + signature in order to interoperate with openssl which + expects this format for signature verification. + + The serialized form is captured both to avoid ambiguity in + how the provenance is marshalled to json as well to prevent + incompatibilities with future changes. + """ + + provenance = proto.Field( + proto.MESSAGE, + number=1, + message=g_provenance.BuildProvenance, + ) + provenance_bytes = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/common.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/common.py new file mode 100644 index 0000000..b23e80f --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/types/common.py @@ -0,0 +1,133 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'NoteKind', + 'RelatedUrl', + 'Signature', + }, +) + + +class NoteKind(proto.Enum): + r"""Kind represents the kinds of notes supported.""" + NOTE_KIND_UNSPECIFIED = 0 + VULNERABILITY = 1 + BUILD = 2 + IMAGE = 3 + PACKAGE = 4 + DEPLOYMENT = 5 + DISCOVERY = 6 + ATTESTATION = 7 + UPGRADE = 8 + + +class RelatedUrl(proto.Message): + r"""Metadata for any related URL information. + Attributes: + url (str): + Specific URL associated with the resource. + label (str): + Label to describe usage of the URL. + """ + + url = proto.Field( + proto.STRING, + number=1, + ) + label = proto.Field( + proto.STRING, + number=2, + ) + + +class Signature(proto.Message): + r"""Verifiers (e.g. Kritis implementations) MUST verify signatures with + respect to the trust anchors defined in policy (e.g. a Kritis + policy). Typically this means that the verifier has been configured + with a map from ``public_key_id`` to public key material (and any + required parameters, e.g. signing algorithm). + + In particular, verification implementations MUST NOT treat the + signature ``public_key_id`` as anything more than a key lookup hint. + The ``public_key_id`` DOES NOT validate or authenticate a public + key; it only provides a mechanism for quickly selecting a public key + ALREADY CONFIGURED on the verifier through a trusted channel. + Verification implementations MUST reject signatures in any of the + following circumstances: + + - The ``public_key_id`` is not recognized by the verifier. + - The public key that ``public_key_id`` refers to does not verify + the signature with respect to the payload. + + The ``signature`` contents SHOULD NOT be "attached" (where the + payload is included with the serialized ``signature`` bytes). + Verifiers MUST ignore any "attached" payload and only verify + signatures with respect to explicitly provided payload (e.g. a + ``payload`` field on the proto message that holds this Signature, or + the canonical serialization of the proto message that holds this + signature). + + Attributes: + signature (bytes): + The content of the signature, an opaque + bytestring. The payload that this signature + verifies MUST be unambiguously provided with the + Signature during verification. A wrapper message + might provide the payload explicitly. + Alternatively, a message might have a canonical + serialization that can always be unambiguously + computed to derive the payload. + public_key_id (str): + The identifier for the public key that verifies this + signature. + + - The ``public_key_id`` is required. + - The ``public_key_id`` MUST be an RFC3986 conformant URI. + - When possible, the ``public_key_id`` SHOULD be an + immutable reference, such as a cryptographic digest. + + Examples of valid ``public_key_id``\ s: + + OpenPGP V4 public key fingerprint: + + - "openpgp4fpr:74FAF3B861BDA0870C7B6DEF607E48D2A663AEEA" + See + https://www.iana.org/assignments/uri-schemes/prov/openpgp4fpr + for more details on this scheme. + + RFC6920 digest-named SubjectPublicKeyInfo (digest of the DER + serialization): + + - "ni:///sha-256;cD9o9Cq6LG3jD0iKXqEi_vdjJGecm_iXkbqVoScViaU" + - "nih:///sha-256;703f68f42aba2c6de30f488a5ea122fef76324679c9bf89791ba95a1271589a5". + """ + + signature = proto.Field( + proto.BYTES, + number=1, + ) + public_key_id = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/cvss.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/cvss.py new file mode 100644 index 0000000..9705a42 --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/types/cvss.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'CVSSv3', + }, +) + + +class CVSSv3(proto.Message): + r"""Common Vulnerability Scoring System version 3. + For details, see https://www.first.org/cvss/specification- + document + + Attributes: + base_score (float): + The base score is a function of the base + metric scores. + exploitability_score (float): + + impact_score (float): + + attack_vector (grafeas.grafeas_v1.types.CVSSv3.AttackVector): + Base Metrics + Represents the intrinsic characteristics of a + vulnerability that are constant over time and + across user environments. + attack_complexity (grafeas.grafeas_v1.types.CVSSv3.AttackComplexity): + + privileges_required (grafeas.grafeas_v1.types.CVSSv3.PrivilegesRequired): + + user_interaction (grafeas.grafeas_v1.types.CVSSv3.UserInteraction): + + scope (grafeas.grafeas_v1.types.CVSSv3.Scope): + + confidentiality_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): + + integrity_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): + + availability_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): + + """ + class AttackVector(proto.Enum): + r"""""" + ATTACK_VECTOR_UNSPECIFIED = 0 + ATTACK_VECTOR_NETWORK = 1 + ATTACK_VECTOR_ADJACENT = 2 + ATTACK_VECTOR_LOCAL = 3 + ATTACK_VECTOR_PHYSICAL = 4 + + class AttackComplexity(proto.Enum): + r"""""" + ATTACK_COMPLEXITY_UNSPECIFIED = 0 + ATTACK_COMPLEXITY_LOW = 1 + ATTACK_COMPLEXITY_HIGH = 2 + + class PrivilegesRequired(proto.Enum): + r"""""" + PRIVILEGES_REQUIRED_UNSPECIFIED = 0 + PRIVILEGES_REQUIRED_NONE = 1 + PRIVILEGES_REQUIRED_LOW = 2 + PRIVILEGES_REQUIRED_HIGH = 3 + + class UserInteraction(proto.Enum): + r"""""" + USER_INTERACTION_UNSPECIFIED = 0 + USER_INTERACTION_NONE = 1 + USER_INTERACTION_REQUIRED = 2 + + class Scope(proto.Enum): + r"""""" + SCOPE_UNSPECIFIED = 0 + SCOPE_UNCHANGED = 1 + SCOPE_CHANGED = 2 + + class Impact(proto.Enum): + r"""""" + IMPACT_UNSPECIFIED = 0 + IMPACT_HIGH = 1 + IMPACT_LOW = 2 + IMPACT_NONE = 3 + + base_score = proto.Field( + proto.FLOAT, + number=1, + ) + exploitability_score = proto.Field( + proto.FLOAT, + number=2, + ) + impact_score = proto.Field( + proto.FLOAT, + number=3, + ) + attack_vector = proto.Field( + proto.ENUM, + number=5, + enum=AttackVector, + ) + attack_complexity = proto.Field( + proto.ENUM, + number=6, + enum=AttackComplexity, + ) + privileges_required = proto.Field( + proto.ENUM, + number=7, + enum=PrivilegesRequired, + ) + user_interaction = proto.Field( + proto.ENUM, + number=8, + enum=UserInteraction, + ) + scope = proto.Field( + proto.ENUM, + number=9, + enum=Scope, + ) + confidentiality_impact = proto.Field( + proto.ENUM, + number=10, + enum=Impact, + ) + integrity_impact = proto.Field( + proto.ENUM, + number=11, + enum=Impact, + ) + availability_impact = proto.Field( + proto.ENUM, + number=12, + enum=Impact, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/deployment.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/deployment.py new file mode 100644 index 0000000..69ac2da --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/types/deployment.py @@ -0,0 +1,109 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'DeploymentNote', + 'DeploymentOccurrence', + }, +) + + +class DeploymentNote(proto.Message): + r"""An artifact that can be deployed in some runtime. + Attributes: + resource_uri (Sequence[str]): + Required. Resource URI for the artifact being + deployed. + """ + + resource_uri = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class DeploymentOccurrence(proto.Message): + r"""The period during which some deployable was active in a + runtime. + + Attributes: + user_email (str): + Identity of the user that triggered this + deployment. + deploy_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Beginning of the lifetime of this + deployment. + undeploy_time (google.protobuf.timestamp_pb2.Timestamp): + End of the lifetime of this deployment. + config (str): + Configuration used to create this deployment. + address (str): + Address of the runtime element hosting this + deployment. + resource_uri (Sequence[str]): + Output only. Resource URI for the artifact + being deployed taken from the deployable field + with the same name. + platform (grafeas.grafeas_v1.types.DeploymentOccurrence.Platform): + Platform hosting this deployment. + """ + class Platform(proto.Enum): + r"""Types of platforms.""" + PLATFORM_UNSPECIFIED = 0 + GKE = 1 + FLEX = 2 + CUSTOM = 3 + + user_email = proto.Field( + proto.STRING, + number=1, + ) + deploy_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + undeploy_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + config = proto.Field( + proto.STRING, + number=4, + ) + address = proto.Field( + proto.STRING, + number=5, + ) + resource_uri = proto.RepeatedField( + proto.STRING, + number=6, + ) + platform = proto.Field( + proto.ENUM, + number=7, + enum=Platform, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/discovery.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/discovery.py new file mode 100644 index 0000000..9f63dad --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/types/discovery.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from grafeas.grafeas_v1.types import common + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'DiscoveryNote', + 'DiscoveryOccurrence', + }, +) + + +class DiscoveryNote(proto.Message): + r"""A note that indicates a type of analysis a provider would perform. + This note exists in a provider's project. A ``Discovery`` occurrence + is created in a consumer's project at the start of analysis. + + Attributes: + analysis_kind (grafeas.grafeas_v1.types.NoteKind): + Required. Immutable. The kind of analysis + that is handled by this discovery. + """ + + analysis_kind = proto.Field( + proto.ENUM, + number=1, + enum=common.NoteKind, + ) + + +class DiscoveryOccurrence(proto.Message): + r"""Provides information about the analysis status of a + discovered resource. + + Attributes: + continuous_analysis (grafeas.grafeas_v1.types.DiscoveryOccurrence.ContinuousAnalysis): + Whether the resource is continuously + analyzed. + analysis_status (grafeas.grafeas_v1.types.DiscoveryOccurrence.AnalysisStatus): + The status of discovery for the resource. + analysis_status_error (google.rpc.status_pb2.Status): + When an error is encountered this will + contain a LocalizedMessage under details to show + to the user. The LocalizedMessage is output only + and populated by the API. + cpe (str): + The CPE of the resource being scanned. + last_scan_time (google.protobuf.timestamp_pb2.Timestamp): + The last time this resource was scanned. + """ + class ContinuousAnalysis(proto.Enum): + r"""Whether the resource is continuously analyzed.""" + CONTINUOUS_ANALYSIS_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + class AnalysisStatus(proto.Enum): + r"""Analysis status for a resource. Currently for initial + analysis only (not updated in continuous analysis). + """ + ANALYSIS_STATUS_UNSPECIFIED = 0 + PENDING = 1 + SCANNING = 2 + FINISHED_SUCCESS = 3 + FINISHED_FAILED = 4 + FINISHED_UNSUPPORTED = 5 + + continuous_analysis = proto.Field( + proto.ENUM, + number=1, + enum=ContinuousAnalysis, + ) + analysis_status = proto.Field( + proto.ENUM, + number=2, + enum=AnalysisStatus, + ) + analysis_status_error = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + cpe = proto.Field( + proto.STRING, + number=4, + ) + last_scan_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/grafeas.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/grafeas.py new file mode 100644 index 0000000..7a229e7 --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/types/grafeas.py @@ -0,0 +1,768 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from grafeas.grafeas_v1.types import attestation as g_attestation +from grafeas.grafeas_v1.types import build as g_build +from grafeas.grafeas_v1.types import common +from grafeas.grafeas_v1.types import deployment as g_deployment +from grafeas.grafeas_v1.types import discovery as g_discovery +from grafeas.grafeas_v1.types import image as g_image +from grafeas.grafeas_v1.types import package as g_package +from grafeas.grafeas_v1.types import upgrade as g_upgrade +from grafeas.grafeas_v1.types import vulnerability as g_vulnerability + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'Occurrence', + 'Note', + 'GetOccurrenceRequest', + 'ListOccurrencesRequest', + 'ListOccurrencesResponse', + 'DeleteOccurrenceRequest', + 'CreateOccurrenceRequest', + 'UpdateOccurrenceRequest', + 'GetNoteRequest', + 'GetOccurrenceNoteRequest', + 'ListNotesRequest', + 'ListNotesResponse', + 'DeleteNoteRequest', + 'CreateNoteRequest', + 'UpdateNoteRequest', + 'ListNoteOccurrencesRequest', + 'ListNoteOccurrencesResponse', + 'BatchCreateNotesRequest', + 'BatchCreateNotesResponse', + 'BatchCreateOccurrencesRequest', + 'BatchCreateOccurrencesResponse', + }, +) + + +class Occurrence(proto.Message): + r"""An instance of an analysis type that has been found on a + resource. + + Attributes: + name (str): + Output only. The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + resource_uri (str): + Required. Immutable. A URI that represents the resource for + which the occurrence applies. For example, + ``https://gcr.io/project/image@sha256:123abc`` for a Docker + image. + note_name (str): + Required. Immutable. The analysis note associated with this + occurrence, in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. This field can + be used as a filter in list requests. + kind (grafeas.grafeas_v1.types.NoteKind): + Output only. This explicitly denotes which of + the occurrence details are specified. This field + can be used as a filter in list requests. + remediation (str): + A description of actions that can be taken to + remedy the note. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this occurrence was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this occurrence was + last updated. + vulnerability (grafeas.grafeas_v1.types.VulnerabilityOccurrence): + Describes a security vulnerability. + build (grafeas.grafeas_v1.types.BuildOccurrence): + Describes a verifiable build. + image (grafeas.grafeas_v1.types.ImageOccurrence): + Describes how this resource derives from the + basis in the associated note. + package (grafeas.grafeas_v1.types.PackageOccurrence): + Describes the installation of a package on + the linked resource. + deployment (grafeas.grafeas_v1.types.DeploymentOccurrence): + Describes the deployment of an artifact on a + runtime. + discovery (grafeas.grafeas_v1.types.DiscoveryOccurrence): + Describes when a resource was discovered. + attestation (grafeas.grafeas_v1.types.AttestationOccurrence): + Describes an attestation of an artifact. + upgrade (grafeas.grafeas_v1.types.UpgradeOccurrence): + Describes an available package upgrade on the + linked resource. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + resource_uri = proto.Field( + proto.STRING, + number=2, + ) + note_name = proto.Field( + proto.STRING, + number=3, + ) + kind = proto.Field( + proto.ENUM, + number=4, + enum=common.NoteKind, + ) + remediation = proto.Field( + proto.STRING, + number=5, + ) + create_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + vulnerability = proto.Field( + proto.MESSAGE, + number=8, + oneof='details', + message=g_vulnerability.VulnerabilityOccurrence, + ) + build = proto.Field( + proto.MESSAGE, + number=9, + oneof='details', + message=g_build.BuildOccurrence, + ) + image = proto.Field( + proto.MESSAGE, + number=10, + oneof='details', + message=g_image.ImageOccurrence, + ) + package = proto.Field( + proto.MESSAGE, + number=11, + oneof='details', + message=g_package.PackageOccurrence, + ) + deployment = proto.Field( + proto.MESSAGE, + number=12, + oneof='details', + message=g_deployment.DeploymentOccurrence, + ) + discovery = proto.Field( + proto.MESSAGE, + number=13, + oneof='details', + message=g_discovery.DiscoveryOccurrence, + ) + attestation = proto.Field( + proto.MESSAGE, + number=14, + oneof='details', + message=g_attestation.AttestationOccurrence, + ) + upgrade = proto.Field( + proto.MESSAGE, + number=15, + oneof='details', + message=g_upgrade.UpgradeOccurrence, + ) + + +class Note(proto.Message): + r"""A type of analysis that can be done for a resource. + Attributes: + name (str): + Output only. The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + short_description (str): + A one sentence description of this note. + long_description (str): + A detailed description of this note. + kind (grafeas.grafeas_v1.types.NoteKind): + Output only. The type of analysis. This field + can be used as a filter in list requests. + related_url (Sequence[grafeas.grafeas_v1.types.RelatedUrl]): + URLs associated with this note. + expiration_time (google.protobuf.timestamp_pb2.Timestamp): + Time of expiration for this note. Empty if + note does not expire. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this note was created. + This field can be used as a filter in list + requests. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this note was last + updated. This field can be used as a filter in + list requests. + related_note_names (Sequence[str]): + Other notes related to this note. + vulnerability (grafeas.grafeas_v1.types.VulnerabilityNote): + A note describing a package vulnerability. + build (grafeas.grafeas_v1.types.BuildNote): + A note describing build provenance for a + verifiable build. + image (grafeas.grafeas_v1.types.ImageNote): + A note describing a base image. + package (grafeas.grafeas_v1.types.PackageNote): + A note describing a package hosted by various + package managers. + deployment (grafeas.grafeas_v1.types.DeploymentNote): + A note describing something that can be + deployed. + discovery (grafeas.grafeas_v1.types.DiscoveryNote): + A note describing the initial analysis of a + resource. + attestation (grafeas.grafeas_v1.types.AttestationNote): + A note describing an attestation role. + upgrade (grafeas.grafeas_v1.types.UpgradeNote): + A note describing available package upgrades. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + short_description = proto.Field( + proto.STRING, + number=2, + ) + long_description = proto.Field( + proto.STRING, + number=3, + ) + kind = proto.Field( + proto.ENUM, + number=4, + enum=common.NoteKind, + ) + related_url = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=common.RelatedUrl, + ) + expiration_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + create_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + related_note_names = proto.RepeatedField( + proto.STRING, + number=9, + ) + vulnerability = proto.Field( + proto.MESSAGE, + number=10, + oneof='type', + message=g_vulnerability.VulnerabilityNote, + ) + build = proto.Field( + proto.MESSAGE, + number=11, + oneof='type', + message=g_build.BuildNote, + ) + image = proto.Field( + proto.MESSAGE, + number=12, + oneof='type', + message=g_image.ImageNote, + ) + package = proto.Field( + proto.MESSAGE, + number=13, + oneof='type', + message=g_package.PackageNote, + ) + deployment = proto.Field( + proto.MESSAGE, + number=14, + oneof='type', + message=g_deployment.DeploymentNote, + ) + discovery = proto.Field( + proto.MESSAGE, + number=15, + oneof='type', + message=g_discovery.DiscoveryNote, + ) + attestation = proto.Field( + proto.MESSAGE, + number=16, + oneof='type', + message=g_attestation.AttestationNote, + ) + upgrade = proto.Field( + proto.MESSAGE, + number=17, + oneof='type', + message=g_upgrade.UpgradeNote, + ) + + +class GetOccurrenceRequest(proto.Message): + r"""Request to get an occurrence. + Attributes: + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListOccurrencesRequest(proto.Message): + r"""Request to list occurrences. + Attributes: + parent (str): + The name of the project to list occurrences for in the form + of ``projects/[PROJECT_ID]``. + filter (str): + The filter expression. + page_size (int): + Number of occurrences to return in the list. + Must be positive. Max allowed page size is 1000. + If not specified, page size defaults to 20. + page_token (str): + Token to provide to skip to a particular spot + in the list. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListOccurrencesResponse(proto.Message): + r"""Response for listing occurrences. + Attributes: + occurrences (Sequence[grafeas.grafeas_v1.types.Occurrence]): + The occurrences requested. + next_page_token (str): + The next pagination token in the list response. It should be + used as ``page_token`` for the following request. An empty + value means no more results. + """ + + @property + def raw_page(self): + return self + + occurrences = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Occurrence', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteOccurrenceRequest(proto.Message): + r"""Request to delete an occurrence. + Attributes: + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateOccurrenceRequest(proto.Message): + r"""Request to create a new occurrence. + Attributes: + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrence is to + be created. + occurrence (grafeas.grafeas_v1.types.Occurrence): + The occurrence to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + occurrence = proto.Field( + proto.MESSAGE, + number=2, + message='Occurrence', + ) + + +class UpdateOccurrenceRequest(proto.Message): + r"""Request to update an occurrence. + Attributes: + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + occurrence (grafeas.grafeas_v1.types.Occurrence): + The updated occurrence. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to update. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + occurrence = proto.Field( + proto.MESSAGE, + number=2, + message='Occurrence', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class GetNoteRequest(proto.Message): + r"""Request to get a note. + Attributes: + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetOccurrenceNoteRequest(proto.Message): + r"""Request to get the note to which the specified occurrence is + attached. + + Attributes: + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListNotesRequest(proto.Message): + r"""Request to list notes. + Attributes: + parent (str): + The name of the project to list notes for in the form of + ``projects/[PROJECT_ID]``. + filter (str): + The filter expression. + page_size (int): + Number of notes to return in the list. Must + be positive. Max allowed page size is 1000. If + not specified, page size defaults to 20. + page_token (str): + Token to provide to skip to a particular spot + in the list. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListNotesResponse(proto.Message): + r"""Response for listing notes. + Attributes: + notes (Sequence[grafeas.grafeas_v1.types.Note]): + The notes requested. + next_page_token (str): + The next pagination token in the list response. It should be + used as ``page_token`` for the following request. An empty + value means no more results. + """ + + @property + def raw_page(self): + return self + + notes = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Note', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteNoteRequest(proto.Message): + r"""Request to delete a note. + Attributes: + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateNoteRequest(proto.Message): + r"""Request to create a new note. + Attributes: + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the note is to be + created. + note_id (str): + The ID to use for this note. + note (grafeas.grafeas_v1.types.Note): + The note to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + note_id = proto.Field( + proto.STRING, + number=2, + ) + note = proto.Field( + proto.MESSAGE, + number=3, + message='Note', + ) + + +class UpdateNoteRequest(proto.Message): + r"""Request to update a note. + Attributes: + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + note (grafeas.grafeas_v1.types.Note): + The updated note. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to update. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + note = proto.Field( + proto.MESSAGE, + number=2, + message='Note', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class ListNoteOccurrencesRequest(proto.Message): + r"""Request to list occurrences for a note. + Attributes: + name (str): + The name of the note to list occurrences for in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + filter (str): + The filter expression. + page_size (int): + Number of occurrences to return in the list. + page_token (str): + Token to provide to skip to a particular spot + in the list. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListNoteOccurrencesResponse(proto.Message): + r"""Response for listing occurrences for a note. + Attributes: + occurrences (Sequence[grafeas.grafeas_v1.types.Occurrence]): + The occurrences attached to the specified + note. + next_page_token (str): + Token to provide to skip to a particular spot + in the list. + """ + + @property + def raw_page(self): + return self + + occurrences = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Occurrence', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class BatchCreateNotesRequest(proto.Message): + r"""Request to create notes in batch. + Attributes: + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the notes are to be + created. + notes (Sequence[grafeas.grafeas_v1.types.BatchCreateNotesRequest.NotesEntry]): + The notes to create. Max allowed length is + 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + notes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='Note', + ) + + +class BatchCreateNotesResponse(proto.Message): + r"""Response for creating notes in batch. + Attributes: + notes (Sequence[grafeas.grafeas_v1.types.Note]): + The notes that were created. + """ + + notes = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Note', + ) + + +class BatchCreateOccurrencesRequest(proto.Message): + r"""Request to create occurrences in batch. + Attributes: + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrences are + to be created. + occurrences (Sequence[grafeas.grafeas_v1.types.Occurrence]): + The occurrences to create. Max allowed length + is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + occurrences = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Occurrence', + ) + + +class BatchCreateOccurrencesResponse(proto.Message): + r"""Response for creating occurrences in batch. + Attributes: + occurrences (Sequence[grafeas.grafeas_v1.types.Occurrence]): + The occurrences that were created. + """ + + occurrences = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Occurrence', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/image.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/image.py new file mode 100644 index 0000000..3ad287f --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/types/image.py @@ -0,0 +1,153 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'Layer', + 'Fingerprint', + 'ImageNote', + 'ImageOccurrence', + }, +) + + +class Layer(proto.Message): + r"""Layer holds metadata specific to a layer of a Docker image. + Attributes: + directive (str): + Required. The recovered Dockerfile directive + used to construct this layer. See + https://docs.docker.com/engine/reference/builder/ + for more information. + arguments (str): + The recovered arguments to the Dockerfile + directive. + """ + + directive = proto.Field( + proto.STRING, + number=1, + ) + arguments = proto.Field( + proto.STRING, + number=2, + ) + + +class Fingerprint(proto.Message): + r"""A set of properties that uniquely identify a given Docker + image. + + Attributes: + v1_name (str): + Required. The layer ID of the final layer in + the Docker image's v1 representation. + v2_blob (Sequence[str]): + Required. The ordered list of v2 blobs that + represent a given image. + v2_name (str): + Output only. The name of the image's v2 blobs computed via: + [bottom] := v2_blob[bottom] [N] := sha256(v2_blob[N] + " " + + v2_name[N+1]) Only the name of the final blob is kept. + """ + + v1_name = proto.Field( + proto.STRING, + number=1, + ) + v2_blob = proto.RepeatedField( + proto.STRING, + number=2, + ) + v2_name = proto.Field( + proto.STRING, + number=3, + ) + + +class ImageNote(proto.Message): + r"""Basis describes the base image portion (Note) of the DockerImage + relationship. Linked occurrences are derived from this or an + equivalent image via: FROM Or an equivalent + reference, e.g., a tag of the resource_url. + + Attributes: + resource_url (str): + Required. Immutable. The resource_url for the resource + representing the basis of associated occurrence images. + fingerprint (grafeas.grafeas_v1.types.Fingerprint): + Required. Immutable. The fingerprint of the + base image. + """ + + resource_url = proto.Field( + proto.STRING, + number=1, + ) + fingerprint = proto.Field( + proto.MESSAGE, + number=2, + message='Fingerprint', + ) + + +class ImageOccurrence(proto.Message): + r"""Details of the derived image portion of the DockerImage + relationship. This image would be produced from a Dockerfile + with FROM . + + Attributes: + fingerprint (grafeas.grafeas_v1.types.Fingerprint): + Required. The fingerprint of the derived + image. + distance (int): + Output only. The number of layers by which + this image differs from the associated image + basis. + layer_info (Sequence[grafeas.grafeas_v1.types.Layer]): + This contains layer-specific metadata, if populated it has + length "distance" and is ordered with [distance] being the + layer immediately following the base image and [1] being the + final layer. + base_resource_url (str): + Output only. This contains the base image URL + for the derived image occurrence. + """ + + fingerprint = proto.Field( + proto.MESSAGE, + number=1, + message='Fingerprint', + ) + distance = proto.Field( + proto.INT32, + number=2, + ) + layer_info = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Layer', + ) + base_resource_url = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/package.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/package.py new file mode 100644 index 0000000..be72e60 --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/types/package.py @@ -0,0 +1,230 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'Architecture', + 'Distribution', + 'Location', + 'PackageNote', + 'PackageOccurrence', + 'Version', + }, +) + + +class Architecture(proto.Enum): + r"""Instruction set architectures supported by various package + managers. + """ + ARCHITECTURE_UNSPECIFIED = 0 + X86 = 1 + X64 = 2 + + +class Distribution(proto.Message): + r"""This represents a particular channel of distribution for a + given package. E.g., Debian's jessie-backports dpkg mirror. + + Attributes: + cpe_uri (str): + Required. The cpe_uri in `CPE + format `__ denoting + the package manager version distributing a package. + architecture (grafeas.grafeas_v1.types.Architecture): + The CPU architecture for which packages in + this distribution channel were built. + latest_version (grafeas.grafeas_v1.types.Version): + The latest available version of this package + in this distribution channel. + maintainer (str): + A freeform string denoting the maintainer of + this package. + url (str): + The distribution channel-specific homepage + for this package. + description (str): + The distribution channel-specific description + of this package. + """ + + cpe_uri = proto.Field( + proto.STRING, + number=1, + ) + architecture = proto.Field( + proto.ENUM, + number=2, + enum='Architecture', + ) + latest_version = proto.Field( + proto.MESSAGE, + number=3, + message='Version', + ) + maintainer = proto.Field( + proto.STRING, + number=4, + ) + url = proto.Field( + proto.STRING, + number=5, + ) + description = proto.Field( + proto.STRING, + number=6, + ) + + +class Location(proto.Message): + r"""An occurrence of a particular package installation found within a + system's filesystem. E.g., glibc was found in + ``/var/lib/dpkg/status``. + + Attributes: + cpe_uri (str): + Required. The CPE URI in `CPE + format `__ denoting + the package manager version distributing a package. + version (grafeas.grafeas_v1.types.Version): + The version installed at this location. + path (str): + The path from which we gathered that this + package/version is installed. + """ + + cpe_uri = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.MESSAGE, + number=2, + message='Version', + ) + path = proto.Field( + proto.STRING, + number=3, + ) + + +class PackageNote(proto.Message): + r"""This represents a particular package that is distributed over + various channels. E.g., glibc (aka libc6) is distributed by + many, at various versions. + + Attributes: + name (str): + Required. Immutable. The name of the package. + distribution (Sequence[grafeas.grafeas_v1.types.Distribution]): + The various channels by which a package is + distributed. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + distribution = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='Distribution', + ) + + +class PackageOccurrence(proto.Message): + r"""Details on how a particular software package was installed on + a system. + + Attributes: + name (str): + Output only. The name of the installed + package. + location (Sequence[grafeas.grafeas_v1.types.Location]): + Required. All of the places within the + filesystem versions of this package have been + found. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + location = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Location', + ) + + +class Version(proto.Message): + r"""Version contains structured information about the version of + a package. + + Attributes: + epoch (int): + Used to correct mistakes in the version + numbering scheme. + name (str): + Required only when version kind is NORMAL. + The main part of the version name. + revision (str): + The iteration of the package build from the + above version. + kind (grafeas.grafeas_v1.types.Version.VersionKind): + Required. Distinguishes between sentinel + MIN/MAX versions and normal versions. + full_name (str): + Human readable version string. This string is + of the form :- and is + only set when kind is NORMAL. + """ + class VersionKind(proto.Enum): + r"""Whether this is an ordinary package version or a sentinel + MIN/MAX version. + """ + VERSION_KIND_UNSPECIFIED = 0 + NORMAL = 1 + MINIMUM = 2 + MAXIMUM = 3 + + epoch = proto.Field( + proto.INT32, + number=1, + ) + name = proto.Field( + proto.STRING, + number=2, + ) + revision = proto.Field( + proto.STRING, + number=3, + ) + kind = proto.Field( + proto.ENUM, + number=4, + enum=VersionKind, + ) + full_name = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/provenance.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/provenance.py new file mode 100644 index 0000000..bb67ca8 --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/types/provenance.py @@ -0,0 +1,528 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'BuildProvenance', + 'Source', + 'FileHashes', + 'Hash', + 'Command', + 'Artifact', + 'SourceContext', + 'AliasContext', + 'CloudRepoSourceContext', + 'GerritSourceContext', + 'GitSourceContext', + 'RepoId', + 'ProjectRepoId', + }, +) + + +class BuildProvenance(proto.Message): + r"""Provenance of a build. Contains all information needed to + verify the full details about the build from source to + completion. + + Attributes: + id (str): + Required. Unique identifier of the build. + project_id (str): + ID of the project. + commands (Sequence[grafeas.grafeas_v1.types.Command]): + Commands requested by the build. + built_artifacts (Sequence[grafeas.grafeas_v1.types.Artifact]): + Output of the build. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the build was created. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which execution of the build was + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which execution of the build was + finished. + creator (str): + E-mail address of the user who initiated this + build. Note that this was the user's e-mail + address at the time the build was initiated; + this address may not represent the same end-user + for all time. + logs_uri (str): + URI where any logs for this provenance were + written. + source_provenance (grafeas.grafeas_v1.types.Source): + Details of the Source input to the build. + trigger_id (str): + Trigger identifier if the build was triggered + automatically; empty if not. + build_options (Sequence[grafeas.grafeas_v1.types.BuildProvenance.BuildOptionsEntry]): + Special options applied to this build. This + is a catch-all field where build providers can + enter any desired additional details. + builder_version (str): + Version string of the builder at the time + this build was executed. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + project_id = proto.Field( + proto.STRING, + number=2, + ) + commands = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Command', + ) + built_artifacts = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Artifact', + ) + create_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + start_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + creator = proto.Field( + proto.STRING, + number=8, + ) + logs_uri = proto.Field( + proto.STRING, + number=9, + ) + source_provenance = proto.Field( + proto.MESSAGE, + number=10, + message='Source', + ) + trigger_id = proto.Field( + proto.STRING, + number=11, + ) + build_options = proto.MapField( + proto.STRING, + proto.STRING, + number=12, + ) + builder_version = proto.Field( + proto.STRING, + number=13, + ) + + +class Source(proto.Message): + r"""Source describes the location of the source used for the + build. + + Attributes: + artifact_storage_source_uri (str): + If provided, the input binary artifacts for + the build came from this location. + file_hashes (Sequence[grafeas.grafeas_v1.types.Source.FileHashesEntry]): + Hash(es) of the build source, which can be + used to verify that the original source + integrity was maintained in the build. + 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. + context (grafeas.grafeas_v1.types.SourceContext): + If provided, the source code used for the + build came from this location. + additional_contexts (Sequence[grafeas.grafeas_v1.types.SourceContext]): + If provided, some of the source code used for + the build may be found in these locations, in + the case where the source repository had + multiple remotes or submodules. This list will + not include the context specified in the context + field. + """ + + artifact_storage_source_uri = proto.Field( + proto.STRING, + number=1, + ) + file_hashes = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='FileHashes', + ) + context = proto.Field( + proto.MESSAGE, + number=3, + message='SourceContext', + ) + additional_contexts = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='SourceContext', + ) + + +class FileHashes(proto.Message): + r"""Container message for hashes of byte content of files, used + in source messages to verify integrity of source input to the + build. + + Attributes: + file_hash (Sequence[grafeas.grafeas_v1.types.Hash]): + Required. 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_ (str): + Required. The type of hash that was + performed, e.g. "SHA-256". + value (bytes): + Required. The hash value. + """ + + type_ = proto.Field( + proto.STRING, + number=1, + ) + value = proto.Field( + proto.BYTES, + number=2, + ) + + +class Command(proto.Message): + r"""Command describes a step performed as part of the build + pipeline. + + Attributes: + name (str): + Required. Name of the command, as presented on the command + line, or if the command is packaged as a Docker container, + as presented to ``docker pull``. + env (Sequence[str]): + Environment variables set before running this + command. + args (Sequence[str]): + Command-line arguments used when executing + this command. + dir_ (str): + Working directory (relative to project source + root) used when running this command. + id (str): + Optional unique identifier for this command, used in + wait_for to reference this command as a dependency. + wait_for (Sequence[str]): + The ID(s) of the command(s) that this command + depends on. + """ + + 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, + ) + + +class Artifact(proto.Message): + r"""Artifact describes a build product. + Attributes: + checksum (str): + Hash or checksum value of a binary, or Docker + Registry 2.0 digest of a container. + id (str): + Artifact ID, if any; for container images, this will be a + URL by digest like + ``gcr.io/projectID/imagename@sha256:123456``. + names (Sequence[str]): + Related artifact names. This may be the path to a binary or + jar file, or in the case of a container build, the name used + to push the container image to Google Container Registry, as + presented to ``docker push``. Note that a single Artifact ID + can have multiple names, for example if two tags are applied + to one image. + """ + + checksum = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + names = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class SourceContext(proto.Message): + r"""A SourceContext is a reference to a tree of files. A + SourceContext together with a path point to a unique revision of + a single file or directory. + + Attributes: + cloud_repo (grafeas.grafeas_v1.types.CloudRepoSourceContext): + A SourceContext referring to a revision in a + Google Cloud Source Repo. + gerrit (grafeas.grafeas_v1.types.GerritSourceContext): + A SourceContext referring to a Gerrit + project. + git (grafeas.grafeas_v1.types.GitSourceContext): + A SourceContext referring to any third party + Git repo (e.g., GitHub). + labels (Sequence[grafeas.grafeas_v1.types.SourceContext.LabelsEntry]): + Labels with user defined metadata. + """ + + cloud_repo = proto.Field( + proto.MESSAGE, + number=1, + oneof='context', + message='CloudRepoSourceContext', + ) + gerrit = proto.Field( + proto.MESSAGE, + number=2, + oneof='context', + message='GerritSourceContext', + ) + git = proto.Field( + proto.MESSAGE, + number=3, + oneof='context', + message='GitSourceContext', + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + + +class AliasContext(proto.Message): + r"""An alias to a repo revision. + Attributes: + kind (grafeas.grafeas_v1.types.AliasContext.Kind): + The alias kind. + name (str): + The alias name. + """ + class Kind(proto.Enum): + r"""The type of an alias.""" + KIND_UNSPECIFIED = 0 + FIXED = 1 + MOVABLE = 2 + OTHER = 4 + + kind = proto.Field( + proto.ENUM, + number=1, + enum=Kind, + ) + name = proto.Field( + proto.STRING, + number=2, + ) + + +class CloudRepoSourceContext(proto.Message): + r"""A CloudRepoSourceContext denotes a particular revision in a + Google Cloud Source Repo. + + Attributes: + repo_id (grafeas.grafeas_v1.types.RepoId): + The ID of the repo. + revision_id (str): + A revision ID. + alias_context (grafeas.grafeas_v1.types.AliasContext): + An alias, which may be a branch or tag. + """ + + repo_id = proto.Field( + proto.MESSAGE, + number=1, + message='RepoId', + ) + revision_id = proto.Field( + proto.STRING, + number=2, + oneof='revision', + ) + alias_context = proto.Field( + proto.MESSAGE, + number=3, + oneof='revision', + message='AliasContext', + ) + + +class GerritSourceContext(proto.Message): + r"""A SourceContext referring to a Gerrit project. + Attributes: + host_uri (str): + The URI of a running Gerrit instance. + gerrit_project (str): + The full project name within the host. + Projects may be nested, so "project/subproject" + is a valid project name. The "repo name" is the + hostURI/project. + revision_id (str): + A revision (commit) ID. + alias_context (grafeas.grafeas_v1.types.AliasContext): + An alias, which may be a branch or tag. + """ + + host_uri = proto.Field( + proto.STRING, + number=1, + ) + gerrit_project = proto.Field( + proto.STRING, + number=2, + ) + revision_id = proto.Field( + proto.STRING, + number=3, + oneof='revision', + ) + alias_context = proto.Field( + proto.MESSAGE, + number=4, + oneof='revision', + message='AliasContext', + ) + + +class GitSourceContext(proto.Message): + r"""A GitSourceContext denotes a particular revision in a third + party Git repository (e.g., GitHub). + + Attributes: + url (str): + Git repository URL. + revision_id (str): + Git commit hash. + """ + + url = proto.Field( + proto.STRING, + number=1, + ) + revision_id = proto.Field( + proto.STRING, + number=2, + ) + + +class RepoId(proto.Message): + r"""A unique identifier for a Cloud Repo. + Attributes: + project_repo_id (grafeas.grafeas_v1.types.ProjectRepoId): + A combination of a project ID and a repo + name. + uid (str): + A server-assigned, globally unique + identifier. + """ + + project_repo_id = proto.Field( + proto.MESSAGE, + number=1, + oneof='id', + message='ProjectRepoId', + ) + uid = proto.Field( + proto.STRING, + number=2, + oneof='id', + ) + + +class ProjectRepoId(proto.Message): + r"""Selects a repo using a Google Cloud Platform project ID + (e.g., winged-cargo-31) and a repo name within that project. + + Attributes: + project_id (str): + The ID of the project. + repo_name (str): + The name of the repo. Leave empty for the + default repo. + """ + + project_id = proto.Field( + proto.STRING, + number=1, + ) + repo_name = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/upgrade.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/upgrade.py new file mode 100644 index 0000000..31269bc --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/types/upgrade.py @@ -0,0 +1,261 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore +from grafeas.grafeas_v1.types import package as g_package + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'UpgradeNote', + 'UpgradeDistribution', + 'WindowsUpdate', + 'UpgradeOccurrence', + }, +) + + +class UpgradeNote(proto.Message): + r"""An Upgrade Note represents a potential upgrade of a package to a + given version. For each package version combination (i.e. bash 4.0, + bash 4.1, bash 4.1.2), there will be an Upgrade Note. For Windows, + windows_update field represents the information related to the + update. + + Attributes: + package (str): + Required for non-Windows OS. The package this + Upgrade is for. + version (grafeas.grafeas_v1.types.Version): + Required for non-Windows OS. The version of + the package in machine + human readable form. + distributions (Sequence[grafeas.grafeas_v1.types.UpgradeDistribution]): + Metadata about the upgrade for each specific + operating system. + windows_update (grafeas.grafeas_v1.types.WindowsUpdate): + Required for Windows OS. Represents the + metadata about the Windows update. + """ + + package = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.MESSAGE, + number=2, + message=g_package.Version, + ) + distributions = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='UpgradeDistribution', + ) + windows_update = proto.Field( + proto.MESSAGE, + number=4, + message='WindowsUpdate', + ) + + +class UpgradeDistribution(proto.Message): + r"""The Upgrade Distribution represents metadata about the + Upgrade for each operating system (CPE). Some distributions have + additional metadata around updates, classifying them into + various categories and severities. + + Attributes: + cpe_uri (str): + Required - The specific operating system this + metadata applies to. See + https://cpe.mitre.org/specification/. + classification (str): + The operating system classification of this Upgrade, as + specified by the upstream operating system upgrade feed. For + Windows the classification is one of the category_ids listed + at + https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ff357803(v=vs.85) + severity (str): + The severity as specified by the upstream + operating system. + cve (Sequence[str]): + The cve tied to this Upgrade. + """ + + cpe_uri = proto.Field( + proto.STRING, + number=1, + ) + classification = proto.Field( + proto.STRING, + number=2, + ) + severity = proto.Field( + proto.STRING, + number=3, + ) + cve = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class WindowsUpdate(proto.Message): + r"""Windows Update represents the metadata about the update for + the Windows operating system. The fields in this message come + from the Windows Update API documented at + https://docs.microsoft.com/en-us/windows/win32/api/wuapi/nn- + wuapi-iupdate. + + Attributes: + identity (grafeas.grafeas_v1.types.WindowsUpdate.Identity): + Required - The unique identifier for the + update. + title (str): + The localized title of the update. + description (str): + The localized description of the update. + categories (Sequence[grafeas.grafeas_v1.types.WindowsUpdate.Category]): + The list of categories to which the update + belongs. + kb_article_ids (Sequence[str]): + The Microsoft Knowledge Base article IDs that + are associated with the update. + support_url (str): + The hyperlink to the support information for + the update. + last_published_timestamp (google.protobuf.timestamp_pb2.Timestamp): + The last published timestamp of the update. + """ + + class Identity(proto.Message): + r"""The unique identifier of the update. + Attributes: + update_id (str): + The revision independent identifier of the + update. + revision (int): + The revision number of the update. + """ + + update_id = proto.Field( + proto.STRING, + number=1, + ) + revision = proto.Field( + proto.INT32, + number=2, + ) + + class Category(proto.Message): + r"""The category to which the update belongs. + Attributes: + category_id (str): + The identifier of the category. + name (str): + The localized name of the category. + """ + + category_id = proto.Field( + proto.STRING, + number=1, + ) + name = proto.Field( + proto.STRING, + number=2, + ) + + identity = proto.Field( + proto.MESSAGE, + number=1, + message=Identity, + ) + title = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + categories = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Category, + ) + kb_article_ids = proto.RepeatedField( + proto.STRING, + number=5, + ) + support_url = proto.Field( + proto.STRING, + number=6, + ) + last_published_timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + + +class UpgradeOccurrence(proto.Message): + r"""An Upgrade Occurrence represents that a specific resource_url could + install a specific upgrade. This presence is supplied via local + sources (i.e. it is present in the mirror and the running system has + noticed its availability). For Windows, both distribution and + windows_update contain information for the Windows update. + + Attributes: + package (str): + Required for non-Windows OS. The package this + Upgrade is for. + parsed_version (grafeas.grafeas_v1.types.Version): + Required for non-Windows OS. The version of + the package in a machine + human readable form. + distribution (grafeas.grafeas_v1.types.UpgradeDistribution): + Metadata about the upgrade for available for the specific + operating system for the resource_url. This allows efficient + filtering, as well as making it easier to use the + occurrence. + windows_update (grafeas.grafeas_v1.types.WindowsUpdate): + Required for Windows OS. Represents the + metadata about the Windows update. + """ + + package = proto.Field( + proto.STRING, + number=1, + ) + parsed_version = proto.Field( + proto.MESSAGE, + number=3, + message=g_package.Version, + ) + distribution = proto.Field( + proto.MESSAGE, + number=4, + message='UpgradeDistribution', + ) + windows_update = proto.Field( + proto.MESSAGE, + number=5, + message='WindowsUpdate', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/vulnerability.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/vulnerability.py new file mode 100644 index 0000000..380d915 --- /dev/null +++ b/owl-bot-staging/v1/grafeas/grafeas_v1/types/vulnerability.py @@ -0,0 +1,424 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore +from grafeas.grafeas_v1.types import common +from grafeas.grafeas_v1.types import cvss +from grafeas.grafeas_v1.types import package + + +__protobuf__ = proto.module( + package='grafeas.v1', + manifest={ + 'Severity', + 'VulnerabilityNote', + 'VulnerabilityOccurrence', + }, +) + + +class Severity(proto.Enum): + r"""Note provider assigned severity/impact ranking.""" + SEVERITY_UNSPECIFIED = 0 + MINIMAL = 1 + LOW = 2 + MEDIUM = 3 + HIGH = 4 + CRITICAL = 5 + + +class VulnerabilityNote(proto.Message): + r"""A security vulnerability that can be found in resources. + Attributes: + cvss_score (float): + The CVSS score of this vulnerability. CVSS + score is on a scale of 0 - 10 where 0 indicates + low severity and 10 indicates high severity. + severity (grafeas.grafeas_v1.types.Severity): + The note provider assigned severity of this + vulnerability. + details (Sequence[grafeas.grafeas_v1.types.VulnerabilityNote.Detail]): + Details of all known distros and packages + affected by this vulnerability. + cvss_v3 (grafeas.grafeas_v1.types.CVSSv3): + The full description of the CVSSv3 for this + vulnerability. + windows_details (Sequence[grafeas.grafeas_v1.types.VulnerabilityNote.WindowsDetail]): + Windows details get their own format because + the information format and model don't match a + normal detail. Specifically Windows updates are + done as patches, thus Windows vulnerabilities + really are a missing package, rather than a + package being at an incorrect version. + source_update_time (google.protobuf.timestamp_pb2.Timestamp): + The time this information was last changed at + the source. This is an upstream timestamp from + the underlying information source - e.g. Ubuntu + security tracker. + """ + + class Detail(proto.Message): + r"""A detail for a distro and package affected by this + vulnerability and its associated fix (if one is available). + + Attributes: + severity_name (str): + The distro assigned severity of this + vulnerability. + description (str): + A vendor-specific description of this + vulnerability. + package_type (str): + The type of package; whether native or non + native (e.g., ruby gems, node.js packages, + etc.). + affected_cpe_uri (str): + Required. The `CPE + URI `__ this + vulnerability affects. + affected_package (str): + Required. The package this vulnerability + affects. + affected_version_start (grafeas.grafeas_v1.types.Version): + The version number at the start of an interval in which this + vulnerability exists. A vulnerability can affect a package + between version numbers that are disjoint sets of intervals + (example: [1.0.0-1.1.0], [2.4.6-2.4.8] and [4.5.6-4.6.8]) + each of which will be represented in its own Detail. If a + specific affected version is provided by a vulnerability + database, affected_version_start and affected_version_end + will be the same in that Detail. + affected_version_end (grafeas.grafeas_v1.types.Version): + The version number at the end of an interval in which this + vulnerability exists. A vulnerability can affect a package + between version numbers that are disjoint sets of intervals + (example: [1.0.0-1.1.0], [2.4.6-2.4.8] and [4.5.6-4.6.8]) + each of which will be represented in its own Detail. If a + specific affected version is provided by a vulnerability + database, affected_version_start and affected_version_end + will be the same in that Detail. + fixed_cpe_uri (str): + The distro recommended `CPE + URI `__ to update to + that contains a fix for this vulnerability. It is possible + for this to be different from the affected_cpe_uri. + fixed_package (str): + The distro recommended package to update to that contains a + fix for this vulnerability. It is possible for this to be + different from the affected_package. + fixed_version (grafeas.grafeas_v1.types.Version): + The distro recommended version to update to + that contains a fix for this vulnerability. + Setting this to VersionKind.MAXIMUM means no + such version is yet available. + is_obsolete (bool): + Whether this detail is obsolete. Occurrences + are expected not to point to obsolete details. + source_update_time (google.protobuf.timestamp_pb2.Timestamp): + The time this information was last changed at + the source. This is an upstream timestamp from + the underlying information source - e.g. Ubuntu + security tracker. + """ + + severity_name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + package_type = proto.Field( + proto.STRING, + number=3, + ) + affected_cpe_uri = proto.Field( + proto.STRING, + number=4, + ) + affected_package = proto.Field( + proto.STRING, + number=5, + ) + affected_version_start = proto.Field( + proto.MESSAGE, + number=6, + message=package.Version, + ) + affected_version_end = proto.Field( + proto.MESSAGE, + number=7, + message=package.Version, + ) + fixed_cpe_uri = proto.Field( + proto.STRING, + number=8, + ) + fixed_package = proto.Field( + proto.STRING, + number=9, + ) + fixed_version = proto.Field( + proto.MESSAGE, + number=10, + message=package.Version, + ) + is_obsolete = proto.Field( + proto.BOOL, + number=11, + ) + source_update_time = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + + class WindowsDetail(proto.Message): + r""" + Attributes: + cpe_uri (str): + Required. The `CPE + URI `__ this + vulnerability affects. + name (str): + Required. The name of this vulnerability. + description (str): + The description of this vulnerability. + fixing_kbs (Sequence[grafeas.grafeas_v1.types.VulnerabilityNote.WindowsDetail.KnowledgeBase]): + Required. The names of the KBs which have + hotfixes to mitigate this vulnerability. Note + that there may be multiple hotfixes (and thus + multiple KBs) that mitigate a given + vulnerability. Currently any listed KBs presence + is considered a fix. + """ + + class KnowledgeBase(proto.Message): + r""" + Attributes: + name (str): + The KB name (generally of the form KB[0-9]+ (e.g., + KB123456)). + url (str): + A link to the KB in the [Windows update catalog] + (https://www.catalog.update.microsoft.com/). + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + url = proto.Field( + proto.STRING, + number=2, + ) + + cpe_uri = proto.Field( + proto.STRING, + number=1, + ) + name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + fixing_kbs = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='VulnerabilityNote.WindowsDetail.KnowledgeBase', + ) + + cvss_score = proto.Field( + proto.FLOAT, + number=1, + ) + severity = proto.Field( + proto.ENUM, + number=2, + enum='Severity', + ) + details = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=Detail, + ) + cvss_v3 = proto.Field( + proto.MESSAGE, + number=4, + message=cvss.CVSSv3, + ) + windows_details = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=WindowsDetail, + ) + source_update_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class VulnerabilityOccurrence(proto.Message): + r"""An occurrence of a severity vulnerability on a resource. + Attributes: + type_ (str): + The type of package; whether native or non + native (e.g., ruby gems, node.js packages, + etc.). + severity (grafeas.grafeas_v1.types.Severity): + Output only. The note provider assigned + severity of this vulnerability. + cvss_score (float): + Output only. The CVSS score of this + vulnerability. CVSS score is on a scale of 0 - + 10 where 0 indicates low severity and 10 + indicates high severity. + package_issue (Sequence[grafeas.grafeas_v1.types.VulnerabilityOccurrence.PackageIssue]): + Required. The set of affected locations and + their fixes (if available) within the associated + resource. + short_description (str): + Output only. A one sentence description of + this vulnerability. + long_description (str): + Output only. A detailed description of this + vulnerability. + related_urls (Sequence[grafeas.grafeas_v1.types.RelatedUrl]): + Output only. URLs related to this + vulnerability. + effective_severity (grafeas.grafeas_v1.types.Severity): + The distro assigned severity for this + vulnerability when it is available, otherwise + this is the note provider assigned severity. + fix_available (bool): + Output only. Whether at least one of the + affected packages has a fix available. + """ + + class PackageIssue(proto.Message): + r"""A detail for a distro and package this vulnerability + occurrence was found in and its associated fix (if one is + available). + + Attributes: + affected_cpe_uri (str): + Required. The `CPE + URI `__ this + vulnerability was found in. + affected_package (str): + Required. The package this vulnerability was + found in. + affected_version (grafeas.grafeas_v1.types.Version): + Required. The version of the package that is + installed on the resource affected by this + vulnerability. + fixed_cpe_uri (str): + The `CPE URI `__ this + vulnerability was fixed in. It is possible for this to be + different from the affected_cpe_uri. + fixed_package (str): + The package this vulnerability was fixed in. It is possible + for this to be different from the affected_package. + fixed_version (grafeas.grafeas_v1.types.Version): + Required. The version of the package this + vulnerability was fixed in. Setting this to + VersionKind.MAXIMUM means no fix is yet + available. + fix_available (bool): + Output only. Whether a fix is available for + this package. + """ + + affected_cpe_uri = proto.Field( + proto.STRING, + number=1, + ) + affected_package = proto.Field( + proto.STRING, + number=2, + ) + affected_version = proto.Field( + proto.MESSAGE, + number=3, + message=package.Version, + ) + fixed_cpe_uri = proto.Field( + proto.STRING, + number=4, + ) + fixed_package = proto.Field( + proto.STRING, + number=5, + ) + fixed_version = proto.Field( + proto.MESSAGE, + number=6, + message=package.Version, + ) + fix_available = proto.Field( + proto.BOOL, + number=7, + ) + + type_ = proto.Field( + proto.STRING, + number=1, + ) + severity = proto.Field( + proto.ENUM, + number=2, + enum='Severity', + ) + cvss_score = proto.Field( + proto.FLOAT, + number=3, + ) + package_issue = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=PackageIssue, + ) + short_description = proto.Field( + proto.STRING, + number=5, + ) + long_description = proto.Field( + proto.STRING, + number=6, + ) + related_urls = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=common.RelatedUrl, + ) + effective_severity = proto.Field( + proto.ENUM, + number=8, + enum='Severity', + ) + fix_available = proto.Field( + proto.BOOL, + number=9, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 0000000..4505b48 --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 0000000..c01f245 --- /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=grafeas/grafeas_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', + 'grafeas', + ) + + +@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_grafeas_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_grafeas_v1_keywords.py new file mode 100644 index 0000000..f8eaf65 --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_grafeas_v1_keywords.py @@ -0,0 +1,189 @@ +#! /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 grafeasCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_create_notes': ('parent', 'notes', ), + 'batch_create_occurrences': ('parent', 'occurrences', ), + 'create_note': ('parent', 'note_id', 'note', ), + 'create_occurrence': ('parent', 'occurrence', ), + 'delete_note': ('name', ), + 'delete_occurrence': ('name', ), + 'get_note': ('name', ), + 'get_occurrence': ('name', ), + 'get_occurrence_note': ('name', ), + 'list_note_occurrences': ('name', 'filter', 'page_size', 'page_token', ), + 'list_notes': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_occurrences': ('parent', 'filter', 'page_size', 'page_token', ), + 'update_note': ('name', 'note', 'update_mask', ), + 'update_occurrence': ('name', 'occurrence', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: 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=grafeasCallTransformer(), +): + """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 grafeas client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 0000000..3b22890 --- /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='grafeas-grafeas', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('grafeas',), + 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 0000000..b54a5fc --- /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 0000000..b54a5fc --- /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 0000000..b54a5fc --- /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/grafeas_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/grafeas_v1/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/grafeas_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/grafeas_v1/test_grafeas.py b/owl-bot-staging/v1/tests/unit/gapic/grafeas_v1/test_grafeas.py new file mode 100644 index 0000000..35fa33e --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/grafeas_v1/test_grafeas.py @@ -0,0 +1,4957 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from grafeas.grafeas_v1.services.grafeas import GrafeasAsyncClient +from grafeas.grafeas_v1.services.grafeas import GrafeasClient +from grafeas.grafeas_v1.services.grafeas import pagers +from grafeas.grafeas_v1.services.grafeas import transports +from grafeas.grafeas_v1.services.grafeas.transports.base import _GOOGLE_AUTH_VERSION +from grafeas.grafeas_v1.types import attestation +from grafeas.grafeas_v1.types import build +from grafeas.grafeas_v1.types import common +from grafeas.grafeas_v1.types import cvss +from grafeas.grafeas_v1.types import deployment +from grafeas.grafeas_v1.types import discovery +from grafeas.grafeas_v1.types import grafeas +from grafeas.grafeas_v1.types import image +from grafeas.grafeas_v1.types import package +from grafeas.grafeas_v1.types import provenance +from grafeas.grafeas_v1.types import upgrade +from grafeas.grafeas_v1.types import vulnerability +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 GrafeasClient._get_default_mtls_endpoint(None) is None + assert GrafeasClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert GrafeasClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert GrafeasClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert GrafeasClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert GrafeasClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + GrafeasClient, + GrafeasAsyncClient, +]) +def test_grafeas_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 == 'containeranalysis.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.GrafeasGrpcTransport, "grpc"), + (transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_grafeas_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", [ + GrafeasClient, + GrafeasAsyncClient, +]) +def test_grafeas_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 == 'containeranalysis.googleapis.com:443' + + +def test_grafeas_client_get_transport_class(): + transport = GrafeasClient.get_transport_class() + available_transports = [ + transports.GrafeasGrpcTransport, + ] + assert transport in available_transports + + transport = GrafeasClient.get_transport_class("grpc") + assert transport == transports.GrafeasGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (GrafeasClient, transports.GrafeasGrpcTransport, "grpc"), + (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(GrafeasClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GrafeasClient)) +@mock.patch.object(GrafeasAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GrafeasAsyncClient)) +def test_grafeas_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(GrafeasClient, '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(GrafeasClient, '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", [ + (GrafeasClient, transports.GrafeasGrpcTransport, "grpc", "true"), + (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (GrafeasClient, transports.GrafeasGrpcTransport, "grpc", "false"), + (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(GrafeasClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GrafeasClient)) +@mock.patch.object(GrafeasAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GrafeasAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_grafeas_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", [ + (GrafeasClient, transports.GrafeasGrpcTransport, "grpc"), + (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_grafeas_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", [ + (GrafeasClient, transports.GrafeasGrpcTransport, "grpc"), + (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_grafeas_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_grafeas_client_client_options_from_dict(): + with mock.patch('grafeas.grafeas_v1.services.grafeas.transports.GrafeasGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = GrafeasClient( + 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_get_occurrence(transport: str = 'grpc', request_type=grafeas.GetOccurrenceRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_value', + vulnerability=vulnerability.VulnerabilityOccurrence(type_='type__value'), + ) + response = client.get_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.GetOccurrenceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == 'name_value' + assert response.resource_uri == 'resource_uri_value' + assert response.note_name == 'note_name_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == 'remediation_value' + + +def test_get_occurrence_from_dict(): + test_get_occurrence(request_type=dict) + + +def test_get_occurrence_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 = GrafeasClient( + 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_occurrence), + '__call__') as call: + client.get_occurrence() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.GetOccurrenceRequest() + + +@pytest.mark.asyncio +async def test_get_occurrence_async(transport: str = 'grpc_asyncio', request_type=grafeas.GetOccurrenceRequest): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_value', + )) + response = await client.get_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.GetOccurrenceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == 'name_value' + assert response.resource_uri == 'resource_uri_value' + assert response.note_name == 'note_name_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == 'remediation_value' + + +@pytest.mark.asyncio +async def test_get_occurrence_async_from_dict(): + await test_get_occurrence_async(request_type=dict) + + +def test_get_occurrence_field_headers(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.GetOccurrenceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence), + '__call__') as call: + call.return_value = grafeas.Occurrence() + client.get_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_occurrence_field_headers_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.GetOccurrenceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + await client.get_occurrence(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_occurrence_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_occurrence( + 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_occurrence_flattened_error(): + client = GrafeasClient( + 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_occurrence( + grafeas.GetOccurrenceRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_occurrence_flattened_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_occurrence( + 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_occurrence_flattened_error_async(): + client = GrafeasAsyncClient( + 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_occurrence( + grafeas.GetOccurrenceRequest(), + name='name_value', + ) + + +def test_list_occurrences(transport: str = 'grpc', request_type=grafeas.ListOccurrencesRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListOccurrencesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.ListOccurrencesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOccurrencesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_occurrences_from_dict(): + test_list_occurrences(request_type=dict) + + +def test_list_occurrences_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 = GrafeasClient( + 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_occurrences), + '__call__') as call: + client.list_occurrences() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.ListOccurrencesRequest() + + +@pytest.mark.asyncio +async def test_list_occurrences_async(transport: str = 'grpc_asyncio', request_type=grafeas.ListOccurrencesRequest): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListOccurrencesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.ListOccurrencesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOccurrencesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_occurrences_async_from_dict(): + await test_list_occurrences_async(request_type=dict) + + +def test_list_occurrences_field_headers(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.ListOccurrencesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__') as call: + call.return_value = grafeas.ListOccurrencesResponse() + client.list_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_occurrences_field_headers_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.ListOccurrencesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListOccurrencesResponse()) + await client.list_occurrences(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_occurrences_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListOccurrencesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_occurrences( + parent='parent_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].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +def test_list_occurrences_flattened_error(): + client = GrafeasClient( + 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_occurrences( + grafeas.ListOccurrencesRequest(), + parent='parent_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_list_occurrences_flattened_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListOccurrencesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListOccurrencesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_occurrences( + parent='parent_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].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_list_occurrences_flattened_error_async(): + client = GrafeasAsyncClient( + 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_occurrences( + grafeas.ListOccurrencesRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_occurrences_pager(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_occurrences(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, grafeas.Occurrence) + for i in results) + +def test_list_occurrences_pages(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + pages = list(client.list_occurrences(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_occurrences_async_pager(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_occurrences(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, grafeas.Occurrence) + for i in responses) + +@pytest.mark.asyncio +async def test_list_occurrences_async_pages(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_occurrences(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_occurrence(transport: str = 'grpc', request_type=grafeas.DeleteOccurrenceRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.DeleteOccurrenceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_occurrence_from_dict(): + test_delete_occurrence(request_type=dict) + + +def test_delete_occurrence_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 = GrafeasClient( + 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_occurrence), + '__call__') as call: + client.delete_occurrence() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.DeleteOccurrenceRequest() + + +@pytest.mark.asyncio +async def test_delete_occurrence_async(transport: str = 'grpc_asyncio', request_type=grafeas.DeleteOccurrenceRequest): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.DeleteOccurrenceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_occurrence_async_from_dict(): + await test_delete_occurrence_async(request_type=dict) + + +def test_delete_occurrence_field_headers(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.DeleteOccurrenceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), + '__call__') as call: + call.return_value = None + client.delete_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_occurrence_field_headers_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.DeleteOccurrenceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_occurrence(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_occurrence_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), + '__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_occurrence( + 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_occurrence_flattened_error(): + client = GrafeasClient( + 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_occurrence( + grafeas.DeleteOccurrenceRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_occurrence_flattened_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), + '__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_occurrence( + 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_occurrence_flattened_error_async(): + client = GrafeasAsyncClient( + 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_occurrence( + grafeas.DeleteOccurrenceRequest(), + name='name_value', + ) + + +def test_create_occurrence(transport: str = 'grpc', request_type=grafeas.CreateOccurrenceRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_value', + vulnerability=vulnerability.VulnerabilityOccurrence(type_='type__value'), + ) + response = client.create_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.CreateOccurrenceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == 'name_value' + assert response.resource_uri == 'resource_uri_value' + assert response.note_name == 'note_name_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == 'remediation_value' + + +def test_create_occurrence_from_dict(): + test_create_occurrence(request_type=dict) + + +def test_create_occurrence_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 = GrafeasClient( + 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_occurrence), + '__call__') as call: + client.create_occurrence() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.CreateOccurrenceRequest() + + +@pytest.mark.asyncio +async def test_create_occurrence_async(transport: str = 'grpc_asyncio', request_type=grafeas.CreateOccurrenceRequest): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_value', + )) + response = await client.create_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.CreateOccurrenceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == 'name_value' + assert response.resource_uri == 'resource_uri_value' + assert response.note_name == 'note_name_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == 'remediation_value' + + +@pytest.mark.asyncio +async def test_create_occurrence_async_from_dict(): + await test_create_occurrence_async(request_type=dict) + + +def test_create_occurrence_field_headers(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.CreateOccurrenceRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), + '__call__') as call: + call.return_value = grafeas.Occurrence() + client.create_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_occurrence_field_headers_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.CreateOccurrenceRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + await client.create_occurrence(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_occurrence_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_occurrence( + parent='parent_value', + occurrence=grafeas.Occurrence(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].parent == 'parent_value' + assert args[0].occurrence == grafeas.Occurrence(name='name_value') + + +def test_create_occurrence_flattened_error(): + client = GrafeasClient( + 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_occurrence( + grafeas.CreateOccurrenceRequest(), + parent='parent_value', + occurrence=grafeas.Occurrence(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_occurrence_flattened_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_occurrence( + parent='parent_value', + occurrence=grafeas.Occurrence(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].parent == 'parent_value' + assert args[0].occurrence == grafeas.Occurrence(name='name_value') + + +@pytest.mark.asyncio +async def test_create_occurrence_flattened_error_async(): + client = GrafeasAsyncClient( + 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_occurrence( + grafeas.CreateOccurrenceRequest(), + parent='parent_value', + occurrence=grafeas.Occurrence(name='name_value'), + ) + + +def test_batch_create_occurrences(transport: str = 'grpc', request_type=grafeas.BatchCreateOccurrencesRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateOccurrencesResponse( + ) + response = client.batch_create_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.BatchCreateOccurrencesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.BatchCreateOccurrencesResponse) + + +def test_batch_create_occurrences_from_dict(): + test_batch_create_occurrences(request_type=dict) + + +def test_batch_create_occurrences_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 = GrafeasClient( + 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.batch_create_occurrences), + '__call__') as call: + client.batch_create_occurrences() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.BatchCreateOccurrencesRequest() + + +@pytest.mark.asyncio +async def test_batch_create_occurrences_async(transport: str = 'grpc_asyncio', request_type=grafeas.BatchCreateOccurrencesRequest): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateOccurrencesResponse( + )) + response = await client.batch_create_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.BatchCreateOccurrencesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.BatchCreateOccurrencesResponse) + + +@pytest.mark.asyncio +async def test_batch_create_occurrences_async_from_dict(): + await test_batch_create_occurrences_async(request_type=dict) + + +def test_batch_create_occurrences_field_headers(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.BatchCreateOccurrencesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), + '__call__') as call: + call.return_value = grafeas.BatchCreateOccurrencesResponse() + client.batch_create_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_batch_create_occurrences_field_headers_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.BatchCreateOccurrencesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateOccurrencesResponse()) + await client.batch_create_occurrences(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_batch_create_occurrences_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateOccurrencesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_create_occurrences( + parent='parent_value', + occurrences=[grafeas.Occurrence(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].parent == 'parent_value' + assert args[0].occurrences == [grafeas.Occurrence(name='name_value')] + + +def test_batch_create_occurrences_flattened_error(): + client = GrafeasClient( + 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.batch_create_occurrences( + grafeas.BatchCreateOccurrencesRequest(), + parent='parent_value', + occurrences=[grafeas.Occurrence(name='name_value')], + ) + + +@pytest.mark.asyncio +async def test_batch_create_occurrences_flattened_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateOccurrencesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateOccurrencesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_create_occurrences( + parent='parent_value', + occurrences=[grafeas.Occurrence(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].parent == 'parent_value' + assert args[0].occurrences == [grafeas.Occurrence(name='name_value')] + + +@pytest.mark.asyncio +async def test_batch_create_occurrences_flattened_error_async(): + client = GrafeasAsyncClient( + 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.batch_create_occurrences( + grafeas.BatchCreateOccurrencesRequest(), + parent='parent_value', + occurrences=[grafeas.Occurrence(name='name_value')], + ) + + +def test_update_occurrence(transport: str = 'grpc', request_type=grafeas.UpdateOccurrenceRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_value', + vulnerability=vulnerability.VulnerabilityOccurrence(type_='type__value'), + ) + response = client.update_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.UpdateOccurrenceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == 'name_value' + assert response.resource_uri == 'resource_uri_value' + assert response.note_name == 'note_name_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == 'remediation_value' + + +def test_update_occurrence_from_dict(): + test_update_occurrence(request_type=dict) + + +def test_update_occurrence_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 = GrafeasClient( + 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_occurrence), + '__call__') as call: + client.update_occurrence() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.UpdateOccurrenceRequest() + + +@pytest.mark.asyncio +async def test_update_occurrence_async(transport: str = 'grpc_asyncio', request_type=grafeas.UpdateOccurrenceRequest): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( + name='name_value', + resource_uri='resource_uri_value', + note_name='note_name_value', + kind=common.NoteKind.VULNERABILITY, + remediation='remediation_value', + )) + response = await client.update_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.UpdateOccurrenceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == 'name_value' + assert response.resource_uri == 'resource_uri_value' + assert response.note_name == 'note_name_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == 'remediation_value' + + +@pytest.mark.asyncio +async def test_update_occurrence_async_from_dict(): + await test_update_occurrence_async(request_type=dict) + + +def test_update_occurrence_field_headers(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.UpdateOccurrenceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), + '__call__') as call: + call.return_value = grafeas.Occurrence() + client.update_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_update_occurrence_field_headers_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.UpdateOccurrenceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + await client.update_occurrence(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_update_occurrence_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_occurrence( + name='name_value', + occurrence=grafeas.Occurrence(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].name == 'name_value' + assert args[0].occurrence == grafeas.Occurrence(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_occurrence_flattened_error(): + client = GrafeasClient( + 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_occurrence( + grafeas.UpdateOccurrenceRequest(), + name='name_value', + occurrence=grafeas.Occurrence(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_occurrence_flattened_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_occurrence( + name='name_value', + occurrence=grafeas.Occurrence(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].name == 'name_value' + assert args[0].occurrence == grafeas.Occurrence(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_occurrence_flattened_error_async(): + client = GrafeasAsyncClient( + 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_occurrence( + grafeas.UpdateOccurrenceRequest(), + name='name_value', + occurrence=grafeas.Occurrence(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_occurrence_note(transport: str = 'grpc', request_type=grafeas.GetOccurrenceNoteRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_occurrence_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + vulnerability=vulnerability.VulnerabilityNote(cvss_score=0.1082), + ) + response = client.get_occurrence_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.GetOccurrenceNoteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +def test_get_occurrence_note_from_dict(): + test_get_occurrence_note(request_type=dict) + + +def test_get_occurrence_note_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 = GrafeasClient( + 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_occurrence_note), + '__call__') as call: + client.get_occurrence_note() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.GetOccurrenceNoteRequest() + + +@pytest.mark.asyncio +async def test_get_occurrence_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.GetOccurrenceNoteRequest): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_occurrence_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + )) + response = await client.get_occurrence_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.GetOccurrenceNoteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +@pytest.mark.asyncio +async def test_get_occurrence_note_async_from_dict(): + await test_get_occurrence_note_async(request_type=dict) + + +def test_get_occurrence_note_field_headers(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.GetOccurrenceNoteRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), + '__call__') as call: + call.return_value = grafeas.Note() + client.get_occurrence_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_occurrence_note_field_headers_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.GetOccurrenceNoteRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + await client.get_occurrence_note(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_occurrence_note_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_occurrence_note( + 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_occurrence_note_flattened_error(): + client = GrafeasClient( + 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_occurrence_note( + grafeas.GetOccurrenceNoteRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_occurrence_note_flattened_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_occurrence_note( + 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_occurrence_note_flattened_error_async(): + client = GrafeasAsyncClient( + 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_occurrence_note( + grafeas.GetOccurrenceNoteRequest(), + name='name_value', + ) + + +def test_get_note(transport: str = 'grpc', request_type=grafeas.GetNoteRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + vulnerability=vulnerability.VulnerabilityNote(cvss_score=0.1082), + ) + response = client.get_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.GetNoteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +def test_get_note_from_dict(): + test_get_note(request_type=dict) + + +def test_get_note_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 = GrafeasClient( + 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_note), + '__call__') as call: + client.get_note() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.GetNoteRequest() + + +@pytest.mark.asyncio +async def test_get_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.GetNoteRequest): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + )) + response = await client.get_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.GetNoteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +@pytest.mark.asyncio +async def test_get_note_async_from_dict(): + await test_get_note_async(request_type=dict) + + +def test_get_note_field_headers(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.GetNoteRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_note), + '__call__') as call: + call.return_value = grafeas.Note() + client.get_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_note_field_headers_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.GetNoteRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_note), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + await client.get_note(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_note_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_note( + 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_note_flattened_error(): + client = GrafeasClient( + 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_note( + grafeas.GetNoteRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_note_flattened_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_note( + 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_note_flattened_error_async(): + client = GrafeasAsyncClient( + 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_note( + grafeas.GetNoteRequest(), + name='name_value', + ) + + +def test_list_notes(transport: str = 'grpc', request_type=grafeas.ListNotesRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNotesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.ListNotesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_notes_from_dict(): + test_list_notes(request_type=dict) + + +def test_list_notes_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 = GrafeasClient( + 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_notes), + '__call__') as call: + client.list_notes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.ListNotesRequest() + + +@pytest.mark.asyncio +async def test_list_notes_async(transport: str = 'grpc_asyncio', request_type=grafeas.ListNotesRequest): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNotesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.ListNotesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_notes_async_from_dict(): + await test_list_notes_async(request_type=dict) + + +def test_list_notes_field_headers(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.ListNotesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__') as call: + call.return_value = grafeas.ListNotesResponse() + client.list_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_notes_field_headers_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.ListNotesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNotesResponse()) + await client.list_notes(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_notes_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNotesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_notes( + parent='parent_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].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +def test_list_notes_flattened_error(): + client = GrafeasClient( + 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_notes( + grafeas.ListNotesRequest(), + parent='parent_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_list_notes_flattened_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNotesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNotesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_notes( + parent='parent_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].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_list_notes_flattened_error_async(): + client = GrafeasAsyncClient( + 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_notes( + grafeas.ListNotesRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_notes_pager(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + grafeas.Note(), + ], + next_page_token='abc', + ), + grafeas.ListNotesResponse( + notes=[], + next_page_token='def', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + ], + next_page_token='ghi', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_notes(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, grafeas.Note) + for i in results) + +def test_list_notes_pages(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + grafeas.Note(), + ], + next_page_token='abc', + ), + grafeas.ListNotesResponse( + notes=[], + next_page_token='def', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + ], + next_page_token='ghi', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + ], + ), + RuntimeError, + ) + pages = list(client.list_notes(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_notes_async_pager(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + grafeas.Note(), + ], + next_page_token='abc', + ), + grafeas.ListNotesResponse( + notes=[], + next_page_token='def', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + ], + next_page_token='ghi', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_notes(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, grafeas.Note) + for i in responses) + +@pytest.mark.asyncio +async def test_list_notes_async_pages(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + grafeas.Note(), + ], + next_page_token='abc', + ), + grafeas.ListNotesResponse( + notes=[], + next_page_token='def', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + ], + next_page_token='ghi', + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_notes(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_note(transport: str = 'grpc', request_type=grafeas.DeleteNoteRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.DeleteNoteRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_note_from_dict(): + test_delete_note(request_type=dict) + + +def test_delete_note_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 = GrafeasClient( + 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_note), + '__call__') as call: + client.delete_note() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.DeleteNoteRequest() + + +@pytest.mark.asyncio +async def test_delete_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.DeleteNoteRequest): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.DeleteNoteRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_note_async_from_dict(): + await test_delete_note_async(request_type=dict) + + +def test_delete_note_field_headers(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.DeleteNoteRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_note), + '__call__') as call: + call.return_value = None + client.delete_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_note_field_headers_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.DeleteNoteRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_note), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_note(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_note_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_note), + '__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_note( + 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_note_flattened_error(): + client = GrafeasClient( + 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_note( + grafeas.DeleteNoteRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_note_flattened_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_note), + '__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_note( + 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_note_flattened_error_async(): + client = GrafeasAsyncClient( + 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_note( + grafeas.DeleteNoteRequest(), + name='name_value', + ) + + +def test_create_note(transport: str = 'grpc', request_type=grafeas.CreateNoteRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + vulnerability=vulnerability.VulnerabilityNote(cvss_score=0.1082), + ) + response = client.create_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.CreateNoteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +def test_create_note_from_dict(): + test_create_note(request_type=dict) + + +def test_create_note_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 = GrafeasClient( + 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_note), + '__call__') as call: + client.create_note() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.CreateNoteRequest() + + +@pytest.mark.asyncio +async def test_create_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.CreateNoteRequest): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + )) + response = await client.create_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.CreateNoteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +@pytest.mark.asyncio +async def test_create_note_async_from_dict(): + await test_create_note_async(request_type=dict) + + +def test_create_note_field_headers(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.CreateNoteRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_note), + '__call__') as call: + call.return_value = grafeas.Note() + client.create_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_note_field_headers_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.CreateNoteRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_note), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + await client.create_note(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_note_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_note( + parent='parent_value', + note_id='note_id_value', + note=grafeas.Note(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].parent == 'parent_value' + assert args[0].note_id == 'note_id_value' + assert args[0].note == grafeas.Note(name='name_value') + + +def test_create_note_flattened_error(): + client = GrafeasClient( + 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_note( + grafeas.CreateNoteRequest(), + parent='parent_value', + note_id='note_id_value', + note=grafeas.Note(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_note_flattened_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_note( + parent='parent_value', + note_id='note_id_value', + note=grafeas.Note(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].parent == 'parent_value' + assert args[0].note_id == 'note_id_value' + assert args[0].note == grafeas.Note(name='name_value') + + +@pytest.mark.asyncio +async def test_create_note_flattened_error_async(): + client = GrafeasAsyncClient( + 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_note( + grafeas.CreateNoteRequest(), + parent='parent_value', + note_id='note_id_value', + note=grafeas.Note(name='name_value'), + ) + + +def test_batch_create_notes(transport: str = 'grpc', request_type=grafeas.BatchCreateNotesRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateNotesResponse( + ) + response = client.batch_create_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.BatchCreateNotesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.BatchCreateNotesResponse) + + +def test_batch_create_notes_from_dict(): + test_batch_create_notes(request_type=dict) + + +def test_batch_create_notes_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 = GrafeasClient( + 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.batch_create_notes), + '__call__') as call: + client.batch_create_notes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.BatchCreateNotesRequest() + + +@pytest.mark.asyncio +async def test_batch_create_notes_async(transport: str = 'grpc_asyncio', request_type=grafeas.BatchCreateNotesRequest): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateNotesResponse( + )) + response = await client.batch_create_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.BatchCreateNotesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.BatchCreateNotesResponse) + + +@pytest.mark.asyncio +async def test_batch_create_notes_async_from_dict(): + await test_batch_create_notes_async(request_type=dict) + + +def test_batch_create_notes_field_headers(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.BatchCreateNotesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), + '__call__') as call: + call.return_value = grafeas.BatchCreateNotesResponse() + client.batch_create_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_batch_create_notes_field_headers_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.BatchCreateNotesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateNotesResponse()) + await client.batch_create_notes(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_batch_create_notes_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateNotesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_create_notes( + parent='parent_value', + notes={'key_value': grafeas.Note(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].parent == 'parent_value' + assert args[0].notes == {'key_value': grafeas.Note(name='name_value')} + + +def test_batch_create_notes_flattened_error(): + client = GrafeasClient( + 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.batch_create_notes( + grafeas.BatchCreateNotesRequest(), + parent='parent_value', + notes={'key_value': grafeas.Note(name='name_value')}, + ) + + +@pytest.mark.asyncio +async def test_batch_create_notes_flattened_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateNotesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateNotesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_create_notes( + parent='parent_value', + notes={'key_value': grafeas.Note(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].parent == 'parent_value' + assert args[0].notes == {'key_value': grafeas.Note(name='name_value')} + + +@pytest.mark.asyncio +async def test_batch_create_notes_flattened_error_async(): + client = GrafeasAsyncClient( + 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.batch_create_notes( + grafeas.BatchCreateNotesRequest(), + parent='parent_value', + notes={'key_value': grafeas.Note(name='name_value')}, + ) + + +def test_update_note(transport: str = 'grpc', request_type=grafeas.UpdateNoteRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + vulnerability=vulnerability.VulnerabilityNote(cvss_score=0.1082), + ) + response = client.update_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.UpdateNoteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +def test_update_note_from_dict(): + test_update_note(request_type=dict) + + +def test_update_note_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 = GrafeasClient( + 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_note), + '__call__') as call: + client.update_note() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.UpdateNoteRequest() + + +@pytest.mark.asyncio +async def test_update_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.UpdateNoteRequest): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( + name='name_value', + short_description='short_description_value', + long_description='long_description_value', + kind=common.NoteKind.VULNERABILITY, + related_note_names=['related_note_names_value'], + )) + response = await client.update_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.UpdateNoteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == 'name_value' + assert response.short_description == 'short_description_value' + assert response.long_description == 'long_description_value' + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ['related_note_names_value'] + + +@pytest.mark.asyncio +async def test_update_note_async_from_dict(): + await test_update_note_async(request_type=dict) + + +def test_update_note_field_headers(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.UpdateNoteRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_note), + '__call__') as call: + call.return_value = grafeas.Note() + client.update_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_update_note_field_headers_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.UpdateNoteRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_note), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + await client.update_note(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_update_note_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_note( + name='name_value', + note=grafeas.Note(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].name == 'name_value' + assert args[0].note == grafeas.Note(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_note_flattened_error(): + client = GrafeasClient( + 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_note( + grafeas.UpdateNoteRequest(), + name='name_value', + note=grafeas.Note(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_note_flattened_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_note), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_note( + name='name_value', + note=grafeas.Note(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].name == 'name_value' + assert args[0].note == grafeas.Note(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_note_flattened_error_async(): + client = GrafeasAsyncClient( + 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_note( + grafeas.UpdateNoteRequest(), + name='name_value', + note=grafeas.Note(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_list_note_occurrences(transport: str = 'grpc', request_type=grafeas.ListNoteOccurrencesRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_note_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNoteOccurrencesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_note_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.ListNoteOccurrencesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNoteOccurrencesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_note_occurrences_from_dict(): + test_list_note_occurrences(request_type=dict) + + +def test_list_note_occurrences_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 = GrafeasClient( + 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_note_occurrences), + '__call__') as call: + client.list_note_occurrences() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.ListNoteOccurrencesRequest() + + +@pytest.mark.asyncio +async def test_list_note_occurrences_async(transport: str = 'grpc_asyncio', request_type=grafeas.ListNoteOccurrencesRequest): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_note_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNoteOccurrencesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_note_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.ListNoteOccurrencesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNoteOccurrencesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_note_occurrences_async_from_dict(): + await test_list_note_occurrences_async(request_type=dict) + + +def test_list_note_occurrences_field_headers(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.ListNoteOccurrencesRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__') as call: + call.return_value = grafeas.ListNoteOccurrencesResponse() + client.list_note_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_list_note_occurrences_field_headers_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.ListNoteOccurrencesRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNoteOccurrencesResponse()) + await client.list_note_occurrences(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_list_note_occurrences_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNoteOccurrencesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_note_occurrences( + name='name_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].name == 'name_value' + assert args[0].filter == 'filter_value' + + +def test_list_note_occurrences_flattened_error(): + client = GrafeasClient( + 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_note_occurrences( + grafeas.ListNoteOccurrencesRequest(), + name='name_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_list_note_occurrences_flattened_async(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNoteOccurrencesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNoteOccurrencesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_note_occurrences( + name='name_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].name == 'name_value' + assert args[0].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_list_note_occurrences_flattened_error_async(): + client = GrafeasAsyncClient( + 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_note_occurrences( + grafeas.ListNoteOccurrencesRequest(), + name='name_value', + filter='filter_value', + ) + + +def test_list_note_occurrences_pager(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', ''), + )), + ) + pager = client.list_note_occurrences(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, grafeas.Occurrence) + for i in results) + +def test_list_note_occurrences_pages(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + pages = list(client.list_note_occurrences(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_note_occurrences_async_pager(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_note_occurrences(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, grafeas.Occurrence) + for i in responses) + +@pytest.mark.asyncio +async def test_list_note_occurrences_async_pages(): + client = GrafeasAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token='abc', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[], + next_page_token='def', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token='ghi', + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_note_occurrences(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.GrafeasGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.GrafeasGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GrafeasClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.GrafeasGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GrafeasClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.GrafeasGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = GrafeasClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.GrafeasGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.GrafeasGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.GrafeasGrpcTransport, + transports.GrafeasGrpcAsyncIOTransport, +]) +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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.GrafeasGrpcTransport, + ) + +def test_grafeas_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.GrafeasTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_grafeas_base_transport(): + # Instantiate the base transport. + with mock.patch('grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.GrafeasTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_occurrence', + 'list_occurrences', + 'delete_occurrence', + 'create_occurrence', + 'batch_create_occurrences', + 'update_occurrence', + 'get_occurrence_note', + 'get_note', + 'list_notes', + 'delete_note', + 'create_note', + 'batch_create_notes', + 'update_note', + 'list_note_occurrences', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_grafeas_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('grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GrafeasTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_grafeas_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('grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GrafeasTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + ), + quota_project_id="octopus", + ) + + +def test_grafeas_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('grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GrafeasTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_grafeas_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) + GrafeasClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_grafeas_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) + GrafeasClient() + adc.assert_called_once_with( + scopes=(), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GrafeasGrpcTransport, + transports.GrafeasGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_grafeas_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=(), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GrafeasGrpcTransport, + transports.GrafeasGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_grafeas_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=( +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.GrafeasGrpcTransport, grpc_helpers), + (transports.GrafeasGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_grafeas_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( + "containeranalysis.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( +), + scopes=["1", "2"], + default_host="containeranalysis.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport]) +def test_grafeas_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_grafeas_host_no_port(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='containeranalysis.googleapis.com'), + ) + assert client.transport._host == 'containeranalysis.googleapis.com:443' + + +def test_grafeas_host_with_port(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='containeranalysis.googleapis.com:8000'), + ) + assert client.transport._host == 'containeranalysis.googleapis.com:8000' + +def test_grafeas_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GrafeasGrpcTransport( + 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_grafeas_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GrafeasGrpcAsyncIOTransport( + 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.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport]) +def test_grafeas_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.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport]) +def test_grafeas_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_note_path(): + project = "squid" + note = "clam" + expected = "projects/{project}/notes/{note}".format(project=project, note=note, ) + actual = GrafeasClient.note_path(project, note) + assert expected == actual + + +def test_parse_note_path(): + expected = { + "project": "whelk", + "note": "octopus", + } + path = GrafeasClient.note_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_note_path(path) + assert expected == actual + +def test_occurrence_path(): + project = "oyster" + occurrence = "nudibranch" + expected = "projects/{project}/occurrences/{occurrence}".format(project=project, occurrence=occurrence, ) + actual = GrafeasClient.occurrence_path(project, occurrence) + assert expected == actual + + +def test_parse_occurrence_path(): + expected = { + "project": "cuttlefish", + "occurrence": "mussel", + } + path = GrafeasClient.occurrence_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_occurrence_path(path) + assert expected == actual + +def test_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = GrafeasClient.project_path(project) + assert expected == actual + + +def test_parse_project_path(): + expected = { + "project": "nautilus", + } + path = GrafeasClient.project_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_project_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = GrafeasClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = GrafeasClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = GrafeasClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = GrafeasClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = GrafeasClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = GrafeasClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = GrafeasClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = GrafeasClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = GrafeasClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = GrafeasClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.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.GrafeasTransport, '_prep_wrapped_messages') as prep: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.GrafeasTransport, '_prep_wrapped_messages') as prep: + transport_class = GrafeasClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) From 080c7b237e2bfde8fdaa2b597dfb73334eb13508 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 23 Jul 2021 21:11:23 +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/grafeas/transports/base.py | 2 +- .../services/grafeas/transports/grpc.py | 5 +- .../grafeas/transports/grpc_asyncio.py | 5 +- owl-bot-staging/v1/.coveragerc | 17 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - owl-bot-staging/v1/docs/conf.py | 376 -- .../v1/docs/grafeas_v1/grafeas.rst | 10 - .../v1/docs/grafeas_v1/services.rst | 6 - owl-bot-staging/v1/docs/grafeas_v1/types.rst | 7 - owl-bot-staging/v1/docs/index.rst | 7 - .../v1/grafeas/grafeas/__init__.py | 149 - owl-bot-staging/v1/grafeas/grafeas/py.typed | 2 - .../v1/grafeas/grafeas_v1/__init__.py | 150 - .../v1/grafeas/grafeas_v1/gapic_metadata.json | 163 - .../v1/grafeas/grafeas_v1/py.typed | 2 - .../grafeas/grafeas_v1/services/__init__.py | 15 - .../grafeas_v1/services/grafeas/__init__.py | 22 - .../services/grafeas/async_client.py | 1415 ----- .../grafeas_v1/services/grafeas/client.py | 1567 ------ .../grafeas_v1/services/grafeas/pagers.py | 384 -- .../services/grafeas/transports/__init__.py | 33 - .../services/grafeas/transports/base.py | 406 -- .../services/grafeas/transports/grpc.py | 613 -- .../grafeas/transports/grpc_asyncio.py | 617 -- .../v1/grafeas/grafeas_v1/types/__init__.py | 168 - .../grafeas/grafeas_v1/types/attestation.py | 109 - .../v1/grafeas/grafeas_v1/types/build.py | 79 - .../v1/grafeas/grafeas_v1/types/common.py | 133 - .../v1/grafeas/grafeas_v1/types/cvss.py | 154 - .../v1/grafeas/grafeas_v1/types/deployment.py | 109 - .../v1/grafeas/grafeas_v1/types/discovery.py | 113 - .../v1/grafeas/grafeas_v1/types/grafeas.py | 768 --- .../v1/grafeas/grafeas_v1/types/image.py | 153 - .../v1/grafeas/grafeas_v1/types/package.py | 230 - .../v1/grafeas/grafeas_v1/types/provenance.py | 528 -- .../v1/grafeas/grafeas_v1/types/upgrade.py | 261 - .../grafeas/grafeas_v1/types/vulnerability.py | 424 -- owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 132 - .../v1/scripts/fixup_grafeas_v1_keywords.py | 189 - 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 - .../tests/unit/gapic/grafeas_v1/__init__.py | 16 - .../unit/gapic/grafeas_v1/test_grafeas.py | 4957 ----------------- tests/unit/gapic/grafeas_v1/test_grafeas.py | 6 +- 48 files changed, 12 insertions(+), 14646 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/grafeas_v1/grafeas.rst delete mode 100644 owl-bot-staging/v1/docs/grafeas_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/grafeas_v1/types.rst delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/grafeas/grafeas/__init__.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas/py.typed delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/__init__.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/py.typed delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/__init__.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/async_client.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/client.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/pagers.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/__init__.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/base.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/attestation.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/build.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/common.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/cvss.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/deployment.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/discovery.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/grafeas.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/image.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/package.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/provenance.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/upgrade.py delete mode 100644 owl-bot-staging/v1/grafeas/grafeas_v1/types/vulnerability.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_grafeas_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/grafeas_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/grafeas_v1/test_grafeas.py diff --git a/grafeas/grafeas_v1/services/grafeas/transports/base.py b/grafeas/grafeas_v1/services/grafeas/transports/base.py index 99aa051..620599b 100644 --- a/grafeas/grafeas_v1/services/grafeas/transports/base.py +++ b/grafeas/grafeas_v1/services/grafeas/transports/base.py @@ -97,7 +97,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. diff --git a/grafeas/grafeas_v1/services/grafeas/transports/grpc.py b/grafeas/grafeas_v1/services/grafeas/transports/grpc.py index f4e2ba4..07ec12f 100644 --- a/grafeas/grafeas_v1/services/grafeas/transports/grpc.py +++ b/grafeas/grafeas_v1/services/grafeas/transports/grpc.py @@ -73,6 +73,7 @@ def __init__( 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. @@ -113,6 +114,8 @@ def __init__( 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 @@ -165,7 +168,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py b/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py index 1c61d66..e8af6c5 100644 --- a/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py +++ b/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py @@ -119,6 +119,7 @@ def __init__( 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. @@ -160,6 +161,8 @@ def __init__( 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 @@ -211,7 +214,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index e619077..0000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - grafeas/grafeas/__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 075904e..0000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include grafeas/grafeas *.py -recursive-include grafeas/grafeas_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index 0f87949..0000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Grafeas Grafeas 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 Grafeas Grafeas API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index c3771e8..0000000 --- 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. -# -# -# grafeas-grafeas 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"grafeas-grafeas" -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": "Grafeas 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 = "grafeas-grafeas-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, - "grafeas-grafeas.tex", - u"grafeas-grafeas 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, - "grafeas-grafeas", - u"Grafeas Grafeas 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, - "grafeas-grafeas", - u"grafeas-grafeas Documentation", - author, - "grafeas-grafeas", - "GAPIC library for Grafeas Grafeas 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/grafeas_v1/grafeas.rst b/owl-bot-staging/v1/docs/grafeas_v1/grafeas.rst deleted file mode 100644 index 7339fab..0000000 --- a/owl-bot-staging/v1/docs/grafeas_v1/grafeas.rst +++ /dev/null @@ -1,10 +0,0 @@ -Grafeas -------------------------- - -.. automodule:: grafeas.grafeas_v1.services.grafeas - :members: - :inherited-members: - -.. automodule:: grafeas.grafeas_v1.services.grafeas.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/grafeas_v1/services.rst b/owl-bot-staging/v1/docs/grafeas_v1/services.rst deleted file mode 100644 index ca38222..0000000 --- a/owl-bot-staging/v1/docs/grafeas_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Grafeas Grafeas v1 API -=================================== -.. toctree:: - :maxdepth: 2 - - grafeas diff --git a/owl-bot-staging/v1/docs/grafeas_v1/types.rst b/owl-bot-staging/v1/docs/grafeas_v1/types.rst deleted file mode 100644 index 91237ff..0000000 --- a/owl-bot-staging/v1/docs/grafeas_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Grafeas Grafeas v1 API -================================ - -.. automodule:: grafeas.grafeas_v1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index e0393b8..0000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - grafeas_v1/services - grafeas_v1/types diff --git a/owl-bot-staging/v1/grafeas/grafeas/__init__.py b/owl-bot-staging/v1/grafeas/grafeas/__init__.py deleted file mode 100644 index 0d45ec6..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas/__init__.py +++ /dev/null @@ -1,149 +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 grafeas.grafeas_v1.services.grafeas.client import GrafeasClient -from grafeas.grafeas_v1.services.grafeas.async_client import GrafeasAsyncClient - -from grafeas.grafeas_v1.types.attestation import AttestationNote -from grafeas.grafeas_v1.types.attestation import AttestationOccurrence -from grafeas.grafeas_v1.types.build import BuildNote -from grafeas.grafeas_v1.types.build import BuildOccurrence -from grafeas.grafeas_v1.types.common import RelatedUrl -from grafeas.grafeas_v1.types.common import Signature -from grafeas.grafeas_v1.types.common import NoteKind -from grafeas.grafeas_v1.types.cvss import CVSSv3 -from grafeas.grafeas_v1.types.deployment import DeploymentNote -from grafeas.grafeas_v1.types.deployment import DeploymentOccurrence -from grafeas.grafeas_v1.types.discovery import DiscoveryNote -from grafeas.grafeas_v1.types.discovery import DiscoveryOccurrence -from grafeas.grafeas_v1.types.grafeas import BatchCreateNotesRequest -from grafeas.grafeas_v1.types.grafeas import BatchCreateNotesResponse -from grafeas.grafeas_v1.types.grafeas import BatchCreateOccurrencesRequest -from grafeas.grafeas_v1.types.grafeas import BatchCreateOccurrencesResponse -from grafeas.grafeas_v1.types.grafeas import CreateNoteRequest -from grafeas.grafeas_v1.types.grafeas import CreateOccurrenceRequest -from grafeas.grafeas_v1.types.grafeas import DeleteNoteRequest -from grafeas.grafeas_v1.types.grafeas import DeleteOccurrenceRequest -from grafeas.grafeas_v1.types.grafeas import GetNoteRequest -from grafeas.grafeas_v1.types.grafeas import GetOccurrenceNoteRequest -from grafeas.grafeas_v1.types.grafeas import GetOccurrenceRequest -from grafeas.grafeas_v1.types.grafeas import ListNoteOccurrencesRequest -from grafeas.grafeas_v1.types.grafeas import ListNoteOccurrencesResponse -from grafeas.grafeas_v1.types.grafeas import ListNotesRequest -from grafeas.grafeas_v1.types.grafeas import ListNotesResponse -from grafeas.grafeas_v1.types.grafeas import ListOccurrencesRequest -from grafeas.grafeas_v1.types.grafeas import ListOccurrencesResponse -from grafeas.grafeas_v1.types.grafeas import Note -from grafeas.grafeas_v1.types.grafeas import Occurrence -from grafeas.grafeas_v1.types.grafeas import UpdateNoteRequest -from grafeas.grafeas_v1.types.grafeas import UpdateOccurrenceRequest -from grafeas.grafeas_v1.types.image import Fingerprint -from grafeas.grafeas_v1.types.image import ImageNote -from grafeas.grafeas_v1.types.image import ImageOccurrence -from grafeas.grafeas_v1.types.image import Layer -from grafeas.grafeas_v1.types.package import Distribution -from grafeas.grafeas_v1.types.package import Location -from grafeas.grafeas_v1.types.package import PackageNote -from grafeas.grafeas_v1.types.package import PackageOccurrence -from grafeas.grafeas_v1.types.package import Version -from grafeas.grafeas_v1.types.package import Architecture -from grafeas.grafeas_v1.types.provenance import AliasContext -from grafeas.grafeas_v1.types.provenance import Artifact -from grafeas.grafeas_v1.types.provenance import BuildProvenance -from grafeas.grafeas_v1.types.provenance import CloudRepoSourceContext -from grafeas.grafeas_v1.types.provenance import Command -from grafeas.grafeas_v1.types.provenance import FileHashes -from grafeas.grafeas_v1.types.provenance import GerritSourceContext -from grafeas.grafeas_v1.types.provenance import GitSourceContext -from grafeas.grafeas_v1.types.provenance import Hash -from grafeas.grafeas_v1.types.provenance import ProjectRepoId -from grafeas.grafeas_v1.types.provenance import RepoId -from grafeas.grafeas_v1.types.provenance import Source -from grafeas.grafeas_v1.types.provenance import SourceContext -from grafeas.grafeas_v1.types.upgrade import UpgradeDistribution -from grafeas.grafeas_v1.types.upgrade import UpgradeNote -from grafeas.grafeas_v1.types.upgrade import UpgradeOccurrence -from grafeas.grafeas_v1.types.upgrade import WindowsUpdate -from grafeas.grafeas_v1.types.vulnerability import VulnerabilityNote -from grafeas.grafeas_v1.types.vulnerability import VulnerabilityOccurrence -from grafeas.grafeas_v1.types.vulnerability import Severity - -__all__ = ('GrafeasClient', - 'GrafeasAsyncClient', - 'AttestationNote', - 'AttestationOccurrence', - 'BuildNote', - 'BuildOccurrence', - 'RelatedUrl', - 'Signature', - 'NoteKind', - 'CVSSv3', - 'DeploymentNote', - 'DeploymentOccurrence', - 'DiscoveryNote', - 'DiscoveryOccurrence', - 'BatchCreateNotesRequest', - 'BatchCreateNotesResponse', - 'BatchCreateOccurrencesRequest', - 'BatchCreateOccurrencesResponse', - 'CreateNoteRequest', - 'CreateOccurrenceRequest', - 'DeleteNoteRequest', - 'DeleteOccurrenceRequest', - 'GetNoteRequest', - 'GetOccurrenceNoteRequest', - 'GetOccurrenceRequest', - 'ListNoteOccurrencesRequest', - 'ListNoteOccurrencesResponse', - 'ListNotesRequest', - 'ListNotesResponse', - 'ListOccurrencesRequest', - 'ListOccurrencesResponse', - 'Note', - 'Occurrence', - 'UpdateNoteRequest', - 'UpdateOccurrenceRequest', - 'Fingerprint', - 'ImageNote', - 'ImageOccurrence', - 'Layer', - 'Distribution', - 'Location', - 'PackageNote', - 'PackageOccurrence', - 'Version', - 'Architecture', - 'AliasContext', - 'Artifact', - 'BuildProvenance', - 'CloudRepoSourceContext', - 'Command', - 'FileHashes', - 'GerritSourceContext', - 'GitSourceContext', - 'Hash', - 'ProjectRepoId', - 'RepoId', - 'Source', - 'SourceContext', - 'UpgradeDistribution', - 'UpgradeNote', - 'UpgradeOccurrence', - 'WindowsUpdate', - 'VulnerabilityNote', - 'VulnerabilityOccurrence', - 'Severity', -) diff --git a/owl-bot-staging/v1/grafeas/grafeas/py.typed b/owl-bot-staging/v1/grafeas/grafeas/py.typed deleted file mode 100644 index 846a558..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The grafeas-grafeas package uses inline types. diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/__init__.py b/owl-bot-staging/v1/grafeas/grafeas_v1/__init__.py deleted file mode 100644 index 18faedb..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/__init__.py +++ /dev/null @@ -1,150 +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.grafeas import GrafeasClient -from .services.grafeas import GrafeasAsyncClient - -from .types.attestation import AttestationNote -from .types.attestation import AttestationOccurrence -from .types.build import BuildNote -from .types.build import BuildOccurrence -from .types.common import RelatedUrl -from .types.common import Signature -from .types.common import NoteKind -from .types.cvss import CVSSv3 -from .types.deployment import DeploymentNote -from .types.deployment import DeploymentOccurrence -from .types.discovery import DiscoveryNote -from .types.discovery import DiscoveryOccurrence -from .types.grafeas import BatchCreateNotesRequest -from .types.grafeas import BatchCreateNotesResponse -from .types.grafeas import BatchCreateOccurrencesRequest -from .types.grafeas import BatchCreateOccurrencesResponse -from .types.grafeas import CreateNoteRequest -from .types.grafeas import CreateOccurrenceRequest -from .types.grafeas import DeleteNoteRequest -from .types.grafeas import DeleteOccurrenceRequest -from .types.grafeas import GetNoteRequest -from .types.grafeas import GetOccurrenceNoteRequest -from .types.grafeas import GetOccurrenceRequest -from .types.grafeas import ListNoteOccurrencesRequest -from .types.grafeas import ListNoteOccurrencesResponse -from .types.grafeas import ListNotesRequest -from .types.grafeas import ListNotesResponse -from .types.grafeas import ListOccurrencesRequest -from .types.grafeas import ListOccurrencesResponse -from .types.grafeas import Note -from .types.grafeas import Occurrence -from .types.grafeas import UpdateNoteRequest -from .types.grafeas import UpdateOccurrenceRequest -from .types.image import Fingerprint -from .types.image import ImageNote -from .types.image import ImageOccurrence -from .types.image import Layer -from .types.package import Distribution -from .types.package import Location -from .types.package import PackageNote -from .types.package import PackageOccurrence -from .types.package import Version -from .types.package import Architecture -from .types.provenance import AliasContext -from .types.provenance import Artifact -from .types.provenance import BuildProvenance -from .types.provenance import CloudRepoSourceContext -from .types.provenance import Command -from .types.provenance import FileHashes -from .types.provenance import GerritSourceContext -from .types.provenance import GitSourceContext -from .types.provenance import Hash -from .types.provenance import ProjectRepoId -from .types.provenance import RepoId -from .types.provenance import Source -from .types.provenance import SourceContext -from .types.upgrade import UpgradeDistribution -from .types.upgrade import UpgradeNote -from .types.upgrade import UpgradeOccurrence -from .types.upgrade import WindowsUpdate -from .types.vulnerability import VulnerabilityNote -from .types.vulnerability import VulnerabilityOccurrence -from .types.vulnerability import Severity - -__all__ = ( - 'GrafeasAsyncClient', -'AliasContext', -'Architecture', -'Artifact', -'AttestationNote', -'AttestationOccurrence', -'BatchCreateNotesRequest', -'BatchCreateNotesResponse', -'BatchCreateOccurrencesRequest', -'BatchCreateOccurrencesResponse', -'BuildNote', -'BuildOccurrence', -'BuildProvenance', -'CVSSv3', -'CloudRepoSourceContext', -'Command', -'CreateNoteRequest', -'CreateOccurrenceRequest', -'DeleteNoteRequest', -'DeleteOccurrenceRequest', -'DeploymentNote', -'DeploymentOccurrence', -'DiscoveryNote', -'DiscoveryOccurrence', -'Distribution', -'FileHashes', -'Fingerprint', -'GerritSourceContext', -'GetNoteRequest', -'GetOccurrenceNoteRequest', -'GetOccurrenceRequest', -'GitSourceContext', -'GrafeasClient', -'Hash', -'ImageNote', -'ImageOccurrence', -'Layer', -'ListNoteOccurrencesRequest', -'ListNoteOccurrencesResponse', -'ListNotesRequest', -'ListNotesResponse', -'ListOccurrencesRequest', -'ListOccurrencesResponse', -'Location', -'Note', -'NoteKind', -'Occurrence', -'PackageNote', -'PackageOccurrence', -'ProjectRepoId', -'RelatedUrl', -'RepoId', -'Severity', -'Signature', -'Source', -'SourceContext', -'UpdateNoteRequest', -'UpdateOccurrenceRequest', -'UpgradeDistribution', -'UpgradeNote', -'UpgradeOccurrence', -'Version', -'VulnerabilityNote', -'VulnerabilityOccurrence', -'WindowsUpdate', -) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/gapic_metadata.json b/owl-bot-staging/v1/grafeas/grafeas_v1/gapic_metadata.json deleted file mode 100644 index 77f5ac0..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/gapic_metadata.json +++ /dev/null @@ -1,163 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "grafeas.grafeas_v1", - "protoPackage": "grafeas.v1", - "schema": "1.0", - "services": { - "Grafeas": { - "clients": { - "grpc": { - "libraryClient": "GrafeasClient", - "rpcs": { - "BatchCreateNotes": { - "methods": [ - "batch_create_notes" - ] - }, - "BatchCreateOccurrences": { - "methods": [ - "batch_create_occurrences" - ] - }, - "CreateNote": { - "methods": [ - "create_note" - ] - }, - "CreateOccurrence": { - "methods": [ - "create_occurrence" - ] - }, - "DeleteNote": { - "methods": [ - "delete_note" - ] - }, - "DeleteOccurrence": { - "methods": [ - "delete_occurrence" - ] - }, - "GetNote": { - "methods": [ - "get_note" - ] - }, - "GetOccurrence": { - "methods": [ - "get_occurrence" - ] - }, - "GetOccurrenceNote": { - "methods": [ - "get_occurrence_note" - ] - }, - "ListNoteOccurrences": { - "methods": [ - "list_note_occurrences" - ] - }, - "ListNotes": { - "methods": [ - "list_notes" - ] - }, - "ListOccurrences": { - "methods": [ - "list_occurrences" - ] - }, - "UpdateNote": { - "methods": [ - "update_note" - ] - }, - "UpdateOccurrence": { - "methods": [ - "update_occurrence" - ] - } - } - }, - "grpc-async": { - "libraryClient": "GrafeasAsyncClient", - "rpcs": { - "BatchCreateNotes": { - "methods": [ - "batch_create_notes" - ] - }, - "BatchCreateOccurrences": { - "methods": [ - "batch_create_occurrences" - ] - }, - "CreateNote": { - "methods": [ - "create_note" - ] - }, - "CreateOccurrence": { - "methods": [ - "create_occurrence" - ] - }, - "DeleteNote": { - "methods": [ - "delete_note" - ] - }, - "DeleteOccurrence": { - "methods": [ - "delete_occurrence" - ] - }, - "GetNote": { - "methods": [ - "get_note" - ] - }, - "GetOccurrence": { - "methods": [ - "get_occurrence" - ] - }, - "GetOccurrenceNote": { - "methods": [ - "get_occurrence_note" - ] - }, - "ListNoteOccurrences": { - "methods": [ - "list_note_occurrences" - ] - }, - "ListNotes": { - "methods": [ - "list_notes" - ] - }, - "ListOccurrences": { - "methods": [ - "list_occurrences" - ] - }, - "UpdateNote": { - "methods": [ - "update_note" - ] - }, - "UpdateOccurrence": { - "methods": [ - "update_occurrence" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/py.typed b/owl-bot-staging/v1/grafeas/grafeas_v1/py.typed deleted file mode 100644 index 846a558..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The grafeas-grafeas package uses inline types. diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/services/__init__.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/__init__.py deleted file mode 100644 index 4de6597..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_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/grafeas/grafeas_v1/services/grafeas/__init__.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/__init__.py deleted file mode 100644 index 8ac3361..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/__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 GrafeasClient -from .async_client import GrafeasAsyncClient - -__all__ = ( - 'GrafeasClient', - 'GrafeasAsyncClient', -) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/async_client.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/async_client.py deleted file mode 100644 index fdf1594..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/async_client.py +++ /dev/null @@ -1,1415 +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.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from grafeas.grafeas_v1.services.grafeas import pagers -from grafeas.grafeas_v1.types import attestation -from grafeas.grafeas_v1.types import build -from grafeas.grafeas_v1.types import common -from grafeas.grafeas_v1.types import deployment -from grafeas.grafeas_v1.types import discovery -from grafeas.grafeas_v1.types import grafeas -from grafeas.grafeas_v1.types import image -from grafeas.grafeas_v1.types import package -from grafeas.grafeas_v1.types import upgrade -from grafeas.grafeas_v1.types import vulnerability -from .transports.base import GrafeasTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import GrafeasGrpcAsyncIOTransport -from .client import GrafeasClient - - -class GrafeasAsyncClient: - """`Grafeas `__ API. - - Retrieves analysis results of Cloud components such as Docker - container images. - - Analysis results are stored as a series of occurrences. An - ``Occurrence`` contains information about a specific analysis - instance on a resource. An occurrence refers to a ``Note``. A note - contains details describing the analysis and is generally stored in - a separate project, called a ``Provider``. Multiple occurrences can - refer to the same note. - - For example, an SSL vulnerability could affect multiple images. In - this case, there would be one note for the vulnerability and an - occurrence for each image with the vulnerability referring to that - note. - """ - - _client: GrafeasClient - - DEFAULT_ENDPOINT = GrafeasClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = GrafeasClient.DEFAULT_MTLS_ENDPOINT - - note_path = staticmethod(GrafeasClient.note_path) - parse_note_path = staticmethod(GrafeasClient.parse_note_path) - occurrence_path = staticmethod(GrafeasClient.occurrence_path) - parse_occurrence_path = staticmethod(GrafeasClient.parse_occurrence_path) - project_path = staticmethod(GrafeasClient.project_path) - parse_project_path = staticmethod(GrafeasClient.parse_project_path) - common_billing_account_path = staticmethod(GrafeasClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(GrafeasClient.parse_common_billing_account_path) - common_folder_path = staticmethod(GrafeasClient.common_folder_path) - parse_common_folder_path = staticmethod(GrafeasClient.parse_common_folder_path) - common_organization_path = staticmethod(GrafeasClient.common_organization_path) - parse_common_organization_path = staticmethod(GrafeasClient.parse_common_organization_path) - common_project_path = staticmethod(GrafeasClient.common_project_path) - parse_common_project_path = staticmethod(GrafeasClient.parse_common_project_path) - common_location_path = staticmethod(GrafeasClient.common_location_path) - parse_common_location_path = staticmethod(GrafeasClient.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: - GrafeasAsyncClient: The constructed client. - """ - return GrafeasClient.from_service_account_info.__func__(GrafeasAsyncClient, 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: - GrafeasAsyncClient: The constructed client. - """ - return GrafeasClient.from_service_account_file.__func__(GrafeasAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> GrafeasTransport: - """Returns the transport used by the client instance. - - Returns: - GrafeasTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(GrafeasClient).get_transport_class, type(GrafeasClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, GrafeasTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the grafeas 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, ~.GrafeasTransport]): 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 = GrafeasClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_occurrence(self, - request: grafeas.GetOccurrenceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.Occurrence: - r"""Gets the specified occurrence. - - Args: - request (:class:`grafeas.grafeas_v1.types.GetOccurrenceRequest`): - The request object. Request to get an occurrence. - name (:class:`str`): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - # 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 = grafeas.GetOccurrenceRequest(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_occurrence, - 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=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_occurrences(self, - request: grafeas.ListOccurrencesRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListOccurrencesAsyncPager: - r"""Lists occurrences for the specified project. - - Args: - request (:class:`grafeas.grafeas_v1.types.ListOccurrencesRequest`): - The request object. Request to list occurrences. - parent (:class:`str`): - The name of the project to list occurrences for in the - form of ``projects/[PROJECT_ID]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - The filter expression. - 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: - grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesAsyncPager: - Response for listing occurrences. - 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, 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 = grafeas.ListOccurrencesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - 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_occurrences, - 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=30.0, - ), - default_timeout=30.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.ListOccurrencesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_occurrence(self, - request: grafeas.DeleteOccurrenceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified occurrence. For example, use - this method to delete an occurrence when the occurrence - is no longer applicable for the given resource. - - Args: - request (:class:`grafeas.grafeas_v1.types.DeleteOccurrenceRequest`): - The request object. Request to delete an occurrence. - name (:class:`str`): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # 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 = grafeas.DeleteOccurrenceRequest(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_occurrence, - 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=30.0, - ), - default_timeout=30.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. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def create_occurrence(self, - request: grafeas.CreateOccurrenceRequest = None, - *, - parent: str = None, - occurrence: grafeas.Occurrence = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.Occurrence: - r"""Creates a new occurrence. - - Args: - request (:class:`grafeas.grafeas_v1.types.CreateOccurrenceRequest`): - The request object. Request to create a new occurrence. - parent (:class:`str`): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrence is - to be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrence (:class:`grafeas.grafeas_v1.types.Occurrence`): - The occurrence to create. - This corresponds to the ``occurrence`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - # 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, occurrence]) - if request is 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 = grafeas.CreateOccurrenceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if occurrence is not None: - request.occurrence = occurrence - - # 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_occurrence, - default_timeout=30.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, - ) - - # Done; return the response. - return response - - async def batch_create_occurrences(self, - request: grafeas.BatchCreateOccurrencesRequest = None, - *, - parent: str = None, - occurrences: Sequence[grafeas.Occurrence] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.BatchCreateOccurrencesResponse: - r"""Creates new occurrences in batch. - - Args: - request (:class:`grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest`): - The request object. Request to create occurrences in - batch. - parent (:class:`str`): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrences - are to be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrences (:class:`Sequence[grafeas.grafeas_v1.types.Occurrence]`): - The occurrences to create. Max - allowed length is 1000. - - This corresponds to the ``occurrences`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse: - Response for creating occurrences in - batch. - - """ - # 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, occurrences]) - if request is 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 = grafeas.BatchCreateOccurrencesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if occurrences: - request.occurrences.extend(occurrences) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_create_occurrences, - default_timeout=30.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, - ) - - # Done; return the response. - return response - - async def update_occurrence(self, - request: grafeas.UpdateOccurrenceRequest = None, - *, - name: str = None, - occurrence: grafeas.Occurrence = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.Occurrence: - r"""Updates the specified occurrence. - - Args: - request (:class:`grafeas.grafeas_v1.types.UpdateOccurrenceRequest`): - The request object. Request to update an occurrence. - name (:class:`str`): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrence (:class:`grafeas.grafeas_v1.types.Occurrence`): - The updated occurrence. - This corresponds to the ``occurrence`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The fields 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: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - # 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, occurrence, 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 = grafeas.UpdateOccurrenceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if occurrence is not None: - request.occurrence = occurrence - 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_occurrence, - default_timeout=30.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 get_occurrence_note(self, - request: grafeas.GetOccurrenceNoteRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.Note: - r"""Gets the note attached to the specified occurrence. - Consumer projects can use this method to get a note that - belongs to a provider project. - - Args: - request (:class:`grafeas.grafeas_v1.types.GetOccurrenceNoteRequest`): - The request object. Request to get the note to which the - specified occurrence is attached. - name (:class:`str`): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a resource. - - """ - # 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 = grafeas.GetOccurrenceNoteRequest(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_occurrence_note, - 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=30.0, - ), - default_timeout=30.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 get_note(self, - request: grafeas.GetNoteRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.Note: - r"""Gets the specified note. - - Args: - request (:class:`grafeas.grafeas_v1.types.GetNoteRequest`): - The request object. Request to get a note. - name (:class:`str`): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a resource. - - """ - # 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 = grafeas.GetNoteRequest(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_note, - 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=30.0, - ), - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_notes(self, - request: grafeas.ListNotesRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNotesAsyncPager: - r"""Lists notes for the specified project. - - Args: - request (:class:`grafeas.grafeas_v1.types.ListNotesRequest`): - The request object. Request to list notes. - parent (:class:`str`): - The name of the project to list notes for in the form of - ``projects/[PROJECT_ID]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - The filter expression. - 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: - grafeas.grafeas_v1.services.grafeas.pagers.ListNotesAsyncPager: - Response for listing notes. - 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, 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 = grafeas.ListNotesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - 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_notes, - 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=30.0, - ), - default_timeout=30.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.ListNotesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_note(self, - request: grafeas.DeleteNoteRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified note. - - Args: - request (:class:`grafeas.grafeas_v1.types.DeleteNoteRequest`): - The request object. Request to delete a note. - name (:class:`str`): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # 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 = grafeas.DeleteNoteRequest(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_note, - 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=30.0, - ), - default_timeout=30.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. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def create_note(self, - request: grafeas.CreateNoteRequest = None, - *, - parent: str = None, - note_id: str = None, - note: grafeas.Note = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.Note: - r"""Creates a new note. - - Args: - request (:class:`grafeas.grafeas_v1.types.CreateNoteRequest`): - The request object. Request to create a new note. - parent (:class:`str`): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the note is to be - created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note_id (:class:`str`): - The ID to use for this note. - This corresponds to the ``note_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note (:class:`grafeas.grafeas_v1.types.Note`): - The note to create. - This corresponds to the ``note`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a resource. - - """ - # 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, note_id, note]) - if request is 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 = grafeas.CreateNoteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if note_id is not None: - request.note_id = note_id - if note is not None: - request.note = note - - # 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_note, - default_timeout=30.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, - ) - - # Done; return the response. - return response - - async def batch_create_notes(self, - request: grafeas.BatchCreateNotesRequest = None, - *, - parent: str = None, - notes: Sequence[grafeas.BatchCreateNotesRequest.NotesEntry] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.BatchCreateNotesResponse: - r"""Creates new notes in batch. - - Args: - request (:class:`grafeas.grafeas_v1.types.BatchCreateNotesRequest`): - The request object. Request to create notes in batch. - parent (:class:`str`): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the notes are to - be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notes (:class:`Sequence[grafeas.grafeas_v1.types.BatchCreateNotesRequest.NotesEntry]`): - The notes to create. Max allowed - length is 1000. - - This corresponds to the ``notes`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - grafeas.grafeas_v1.types.BatchCreateNotesResponse: - Response for creating notes in batch. - """ - # 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, notes]) - if request is 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 = grafeas.BatchCreateNotesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - if notes: - request.notes.update(notes) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_create_notes, - default_timeout=30.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, - ) - - # Done; return the response. - return response - - async def update_note(self, - request: grafeas.UpdateNoteRequest = None, - *, - name: str = None, - note: grafeas.Note = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.Note: - r"""Updates the specified note. - - Args: - request (:class:`grafeas.grafeas_v1.types.UpdateNoteRequest`): - The request object. Request to update a note. - name (:class:`str`): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note (:class:`grafeas.grafeas_v1.types.Note`): - The updated note. - This corresponds to the ``note`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The fields 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: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a resource. - - """ - # 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, note, 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 = grafeas.UpdateNoteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if note is not None: - request.note = note - 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_note, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_note_occurrences(self, - request: grafeas.ListNoteOccurrencesRequest = None, - *, - name: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNoteOccurrencesAsyncPager: - r"""Lists occurrences referencing the specified note. - Provider projects can use this method to get all - occurrences across consumer projects referencing the - specified note. - - Args: - request (:class:`grafeas.grafeas_v1.types.ListNoteOccurrencesRequest`): - The request object. Request to list occurrences for a - note. - name (:class:`str`): - The name of the note to list occurrences for in the form - of ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - The filter expression. - 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: - grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesAsyncPager: - Response for listing occurrences for - a note. - 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([name, 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 = grafeas.ListNoteOccurrencesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - 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_note_occurrences, - 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=30.0, - ), - default_timeout=30.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, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListNoteOccurrencesAsyncPager( - 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( - "grafeas-grafeas", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "GrafeasAsyncClient", -) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/client.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/client.py deleted file mode 100644 index 580eb34..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/client.py +++ /dev/null @@ -1,1567 +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.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from grafeas.grafeas_v1.services.grafeas import pagers -from grafeas.grafeas_v1.types import attestation -from grafeas.grafeas_v1.types import build -from grafeas.grafeas_v1.types import common -from grafeas.grafeas_v1.types import deployment -from grafeas.grafeas_v1.types import discovery -from grafeas.grafeas_v1.types import grafeas -from grafeas.grafeas_v1.types import image -from grafeas.grafeas_v1.types import package -from grafeas.grafeas_v1.types import upgrade -from grafeas.grafeas_v1.types import vulnerability -from .transports.base import GrafeasTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import GrafeasGrpcTransport -from .transports.grpc_asyncio import GrafeasGrpcAsyncIOTransport - - -class GrafeasClientMeta(type): - """Metaclass for the Grafeas 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[GrafeasTransport]] - _transport_registry["grpc"] = GrafeasGrpcTransport - _transport_registry["grpc_asyncio"] = GrafeasGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[GrafeasTransport]: - """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 GrafeasClient(metaclass=GrafeasClientMeta): - """`Grafeas `__ API. - - Retrieves analysis results of Cloud components such as Docker - container images. - - Analysis results are stored as a series of occurrences. An - ``Occurrence`` contains information about a specific analysis - instance on a resource. An occurrence refers to a ``Note``. A note - contains details describing the analysis and is generally stored in - a separate project, called a ``Provider``. Multiple occurrences can - refer to the same note. - - For example, an SSL vulnerability could affect multiple images. In - this case, there would be one note for the vulnerability and an - occurrence for each image with the vulnerability referring to that - note. - """ - - @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 = "containeranalysis.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: - GrafeasClient: 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: - GrafeasClient: 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) -> GrafeasTransport: - """Returns the transport used by the client instance. - - Returns: - GrafeasTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def note_path(project: str,note: str,) -> str: - """Returns a fully-qualified note string.""" - return "projects/{project}/notes/{note}".format(project=project, note=note, ) - - @staticmethod - def parse_note_path(path: str) -> Dict[str,str]: - """Parses a note path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/notes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def occurrence_path(project: str,occurrence: str,) -> str: - """Returns a fully-qualified occurrence string.""" - return "projects/{project}/occurrences/{occurrence}".format(project=project, occurrence=occurrence, ) - - @staticmethod - def parse_occurrence_path(path: str) -> Dict[str,str]: - """Parses a occurrence path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/occurrences/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def project_path(project: str,) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_project_path(path: str) -> Dict[str,str]: - """Parses a project path into its component segments.""" - m = re.match(r"^projects/(?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, GrafeasTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the grafeas 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, GrafeasTransport]): 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, GrafeasTransport): - # transport is a GrafeasTransport 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 get_occurrence(self, - request: grafeas.GetOccurrenceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.Occurrence: - r"""Gets the specified occurrence. - - Args: - request (grafeas.grafeas_v1.types.GetOccurrenceRequest): - The request object. Request to get an occurrence. - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - # 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 grafeas.GetOccurrenceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, grafeas.GetOccurrenceRequest): - request = grafeas.GetOccurrenceRequest(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_occurrence] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_occurrences(self, - request: grafeas.ListOccurrencesRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListOccurrencesPager: - r"""Lists occurrences for the specified project. - - Args: - request (grafeas.grafeas_v1.types.ListOccurrencesRequest): - The request object. Request to list occurrences. - parent (str): - The name of the project to list occurrences for in the - form of ``projects/[PROJECT_ID]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - The filter expression. - 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: - grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesPager: - Response for listing occurrences. - 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, 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 grafeas.ListOccurrencesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, grafeas.ListOccurrencesRequest): - request = grafeas.ListOccurrencesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - 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_occurrences] - - # 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.ListOccurrencesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_occurrence(self, - request: grafeas.DeleteOccurrenceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified occurrence. For example, use - this method to delete an occurrence when the occurrence - is no longer applicable for the given resource. - - Args: - request (grafeas.grafeas_v1.types.DeleteOccurrenceRequest): - The request object. Request to delete an occurrence. - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # 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 grafeas.DeleteOccurrenceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, grafeas.DeleteOccurrenceRequest): - request = grafeas.DeleteOccurrenceRequest(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_occurrence] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def create_occurrence(self, - request: grafeas.CreateOccurrenceRequest = None, - *, - parent: str = None, - occurrence: grafeas.Occurrence = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.Occurrence: - r"""Creates a new occurrence. - - Args: - request (grafeas.grafeas_v1.types.CreateOccurrenceRequest): - The request object. Request to create a new occurrence. - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrence is - to be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrence (grafeas.grafeas_v1.types.Occurrence): - The occurrence to create. - This corresponds to the ``occurrence`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - # 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, occurrence]) - if request is 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 grafeas.CreateOccurrenceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, grafeas.CreateOccurrenceRequest): - request = grafeas.CreateOccurrenceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if occurrence is not None: - request.occurrence = occurrence - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_occurrence] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def batch_create_occurrences(self, - request: grafeas.BatchCreateOccurrencesRequest = None, - *, - parent: str = None, - occurrences: Sequence[grafeas.Occurrence] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.BatchCreateOccurrencesResponse: - r"""Creates new occurrences in batch. - - Args: - request (grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest): - The request object. Request to create occurrences in - batch. - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrences - are to be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrences (Sequence[grafeas.grafeas_v1.types.Occurrence]): - The occurrences to create. Max - allowed length is 1000. - - This corresponds to the ``occurrences`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse: - Response for creating occurrences in - batch. - - """ - # 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, occurrences]) - if request is 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 grafeas.BatchCreateOccurrencesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, grafeas.BatchCreateOccurrencesRequest): - request = grafeas.BatchCreateOccurrencesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if occurrences is not None: - request.occurrences = occurrences - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_create_occurrences] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_occurrence(self, - request: grafeas.UpdateOccurrenceRequest = None, - *, - name: str = None, - occurrence: grafeas.Occurrence = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.Occurrence: - r"""Updates the specified occurrence. - - Args: - request (grafeas.grafeas_v1.types.UpdateOccurrenceRequest): - The request object. Request to update an occurrence. - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrence (grafeas.grafeas_v1.types.Occurrence): - The updated occurrence. - This corresponds to the ``occurrence`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields 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: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - # 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, occurrence, 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 grafeas.UpdateOccurrenceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, grafeas.UpdateOccurrenceRequest): - request = grafeas.UpdateOccurrenceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if occurrence is not None: - request.occurrence = occurrence - 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_occurrence] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_occurrence_note(self, - request: grafeas.GetOccurrenceNoteRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.Note: - r"""Gets the note attached to the specified occurrence. - Consumer projects can use this method to get a note that - belongs to a provider project. - - Args: - request (grafeas.grafeas_v1.types.GetOccurrenceNoteRequest): - The request object. Request to get the note to which the - specified occurrence is attached. - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a resource. - - """ - # 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 grafeas.GetOccurrenceNoteRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, grafeas.GetOccurrenceNoteRequest): - request = grafeas.GetOccurrenceNoteRequest(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_occurrence_note] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_note(self, - request: grafeas.GetNoteRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.Note: - r"""Gets the specified note. - - Args: - request (grafeas.grafeas_v1.types.GetNoteRequest): - The request object. Request to get a note. - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a resource. - - """ - # 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 grafeas.GetNoteRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, grafeas.GetNoteRequest): - request = grafeas.GetNoteRequest(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_note] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_notes(self, - request: grafeas.ListNotesRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNotesPager: - r"""Lists notes for the specified project. - - Args: - request (grafeas.grafeas_v1.types.ListNotesRequest): - The request object. Request to list notes. - parent (str): - The name of the project to list notes for in the form of - ``projects/[PROJECT_ID]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - The filter expression. - 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: - grafeas.grafeas_v1.services.grafeas.pagers.ListNotesPager: - Response for listing notes. - 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, 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 grafeas.ListNotesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, grafeas.ListNotesRequest): - request = grafeas.ListNotesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - 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_notes] - - # 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.ListNotesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_note(self, - request: grafeas.DeleteNoteRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified note. - - Args: - request (grafeas.grafeas_v1.types.DeleteNoteRequest): - The request object. Request to delete a note. - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # 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 grafeas.DeleteNoteRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, grafeas.DeleteNoteRequest): - request = grafeas.DeleteNoteRequest(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_note] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def create_note(self, - request: grafeas.CreateNoteRequest = None, - *, - parent: str = None, - note_id: str = None, - note: grafeas.Note = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.Note: - r"""Creates a new note. - - Args: - request (grafeas.grafeas_v1.types.CreateNoteRequest): - The request object. Request to create a new note. - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the note is to be - created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note_id (str): - The ID to use for this note. - This corresponds to the ``note_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note (grafeas.grafeas_v1.types.Note): - The note to create. - This corresponds to the ``note`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a resource. - - """ - # 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, note_id, note]) - if request is 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 grafeas.CreateNoteRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, grafeas.CreateNoteRequest): - request = grafeas.CreateNoteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if note_id is not None: - request.note_id = note_id - if note is not None: - request.note = note - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_note] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def batch_create_notes(self, - request: grafeas.BatchCreateNotesRequest = None, - *, - parent: str = None, - notes: Sequence[grafeas.BatchCreateNotesRequest.NotesEntry] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.BatchCreateNotesResponse: - r"""Creates new notes in batch. - - Args: - request (grafeas.grafeas_v1.types.BatchCreateNotesRequest): - The request object. Request to create notes in batch. - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the notes are to - be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notes (Sequence[grafeas.grafeas_v1.types.BatchCreateNotesRequest.NotesEntry]): - The notes to create. Max allowed - length is 1000. - - This corresponds to the ``notes`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - grafeas.grafeas_v1.types.BatchCreateNotesResponse: - Response for creating notes in batch. - """ - # 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, notes]) - if request is 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 grafeas.BatchCreateNotesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, grafeas.BatchCreateNotesRequest): - request = grafeas.BatchCreateNotesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if notes is not None: - request.notes = notes - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_create_notes] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_note(self, - request: grafeas.UpdateNoteRequest = None, - *, - name: str = None, - note: grafeas.Note = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grafeas.Note: - r"""Updates the specified note. - - Args: - request (grafeas.grafeas_v1.types.UpdateNoteRequest): - The request object. Request to update a note. - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note (grafeas.grafeas_v1.types.Note): - The updated note. - This corresponds to the ``note`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields 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: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a resource. - - """ - # 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, note, 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 grafeas.UpdateNoteRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, grafeas.UpdateNoteRequest): - request = grafeas.UpdateNoteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if note is not None: - request.note = note - 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_note] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_note_occurrences(self, - request: grafeas.ListNoteOccurrencesRequest = None, - *, - name: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNoteOccurrencesPager: - r"""Lists occurrences referencing the specified note. - Provider projects can use this method to get all - occurrences across consumer projects referencing the - specified note. - - Args: - request (grafeas.grafeas_v1.types.ListNoteOccurrencesRequest): - The request object. Request to list occurrences for a - note. - name (str): - The name of the note to list occurrences for in the form - of ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - The filter expression. - 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: - grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesPager: - Response for listing occurrences for - a note. - 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([name, 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 grafeas.ListNoteOccurrencesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, grafeas.ListNoteOccurrencesRequest): - request = grafeas.ListNoteOccurrencesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - 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_note_occurrences] - - # 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, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListNoteOccurrencesPager( - 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( - "grafeas-grafeas", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "GrafeasClient", -) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/pagers.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/pagers.py deleted file mode 100644 index de16137..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/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 grafeas.grafeas_v1.types import grafeas - - -class ListOccurrencesPager: - """A pager for iterating through ``list_occurrences`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``occurrences`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListOccurrences`` requests and continue to iterate - through the ``occurrences`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` - 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[..., grafeas.ListOccurrencesResponse], - request: grafeas.ListOccurrencesRequest, - response: grafeas.ListOccurrencesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (grafeas.grafeas_v1.types.ListOccurrencesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListOccurrencesResponse): - 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 = grafeas.ListOccurrencesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[grafeas.ListOccurrencesResponse]: - 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[grafeas.Occurrence]: - for page in self.pages: - yield from page.occurrences - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListOccurrencesAsyncPager: - """A pager for iterating through ``list_occurrences`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``occurrences`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListOccurrences`` requests and continue to iterate - through the ``occurrences`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` - 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[grafeas.ListOccurrencesResponse]], - request: grafeas.ListOccurrencesRequest, - response: grafeas.ListOccurrencesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (grafeas.grafeas_v1.types.ListOccurrencesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListOccurrencesResponse): - 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 = grafeas.ListOccurrencesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[grafeas.ListOccurrencesResponse]: - 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[grafeas.Occurrence]: - async def async_generator(): - async for page in self.pages: - for response in page.occurrences: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotesPager: - """A pager for iterating through ``list_notes`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListNotesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``notes`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNotes`` requests and continue to iterate - through the ``notes`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListNotesResponse` - 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[..., grafeas.ListNotesResponse], - request: grafeas.ListNotesRequest, - response: grafeas.ListNotesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (grafeas.grafeas_v1.types.ListNotesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListNotesResponse): - 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 = grafeas.ListNotesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[grafeas.ListNotesResponse]: - 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[grafeas.Note]: - for page in self.pages: - yield from page.notes - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotesAsyncPager: - """A pager for iterating through ``list_notes`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListNotesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``notes`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNotes`` requests and continue to iterate - through the ``notes`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListNotesResponse` - 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[grafeas.ListNotesResponse]], - request: grafeas.ListNotesRequest, - response: grafeas.ListNotesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (grafeas.grafeas_v1.types.ListNotesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListNotesResponse): - 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 = grafeas.ListNotesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[grafeas.ListNotesResponse]: - 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[grafeas.Note]: - async def async_generator(): - async for page in self.pages: - for response in page.notes: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNoteOccurrencesPager: - """A pager for iterating through ``list_note_occurrences`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``occurrences`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNoteOccurrences`` requests and continue to iterate - through the ``occurrences`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` - 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[..., grafeas.ListNoteOccurrencesResponse], - request: grafeas.ListNoteOccurrencesRequest, - response: grafeas.ListNoteOccurrencesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (grafeas.grafeas_v1.types.ListNoteOccurrencesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListNoteOccurrencesResponse): - 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 = grafeas.ListNoteOccurrencesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[grafeas.ListNoteOccurrencesResponse]: - 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[grafeas.Occurrence]: - for page in self.pages: - yield from page.occurrences - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNoteOccurrencesAsyncPager: - """A pager for iterating through ``list_note_occurrences`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``occurrences`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNoteOccurrences`` requests and continue to iterate - through the ``occurrences`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` - 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[grafeas.ListNoteOccurrencesResponse]], - request: grafeas.ListNoteOccurrencesRequest, - response: grafeas.ListNoteOccurrencesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (grafeas.grafeas_v1.types.ListNoteOccurrencesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListNoteOccurrencesResponse): - 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 = grafeas.ListNoteOccurrencesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[grafeas.ListNoteOccurrencesResponse]: - 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[grafeas.Occurrence]: - async def async_generator(): - async for page in self.pages: - for response in page.occurrences: - 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/grafeas/grafeas_v1/services/grafeas/transports/__init__.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/__init__.py deleted file mode 100644 index d042d7b..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/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 GrafeasTransport -from .grpc import GrafeasGrpcTransport -from .grpc_asyncio import GrafeasGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[GrafeasTransport]] -_transport_registry['grpc'] = GrafeasGrpcTransport -_transport_registry['grpc_asyncio'] = GrafeasGrpcAsyncIOTransport - -__all__ = ( - 'GrafeasTransport', - 'GrafeasGrpcTransport', - 'GrafeasGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/base.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/base.py deleted file mode 100644 index ca7979d..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/base.py +++ /dev/null @@ -1,406 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.protobuf import empty_pb2 # type: ignore -from grafeas.grafeas_v1.types import grafeas - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'grafeas-grafeas', - ).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 GrafeasTransport(abc.ABC): - """Abstract transport class for Grafeas.""" - - AUTH_SCOPES = ( - ) - - DEFAULT_HOST: str = 'containeranalysis.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.get_occurrence: gapic_v1.method.wrap_method( - self.get_occurrence, - 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=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_occurrences: gapic_v1.method.wrap_method( - self.list_occurrences, - 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=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.delete_occurrence: gapic_v1.method.wrap_method( - self.delete_occurrence, - 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=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.create_occurrence: gapic_v1.method.wrap_method( - self.create_occurrence, - default_timeout=30.0, - client_info=client_info, - ), - self.batch_create_occurrences: gapic_v1.method.wrap_method( - self.batch_create_occurrences, - default_timeout=30.0, - client_info=client_info, - ), - self.update_occurrence: gapic_v1.method.wrap_method( - self.update_occurrence, - default_timeout=30.0, - client_info=client_info, - ), - self.get_occurrence_note: gapic_v1.method.wrap_method( - self.get_occurrence_note, - 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=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.get_note: gapic_v1.method.wrap_method( - self.get_note, - 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=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_notes: gapic_v1.method.wrap_method( - self.list_notes, - 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=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.delete_note: gapic_v1.method.wrap_method( - self.delete_note, - 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=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.create_note: gapic_v1.method.wrap_method( - self.create_note, - default_timeout=30.0, - client_info=client_info, - ), - self.batch_create_notes: gapic_v1.method.wrap_method( - self.batch_create_notes, - default_timeout=30.0, - client_info=client_info, - ), - self.update_note: gapic_v1.method.wrap_method( - self.update_note, - default_timeout=30.0, - client_info=client_info, - ), - self.list_note_occurrences: gapic_v1.method.wrap_method( - self.list_note_occurrences, - 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=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - } - - @property - def get_occurrence(self) -> Callable[ - [grafeas.GetOccurrenceRequest], - Union[ - grafeas.Occurrence, - Awaitable[grafeas.Occurrence] - ]]: - raise NotImplementedError() - - @property - def list_occurrences(self) -> Callable[ - [grafeas.ListOccurrencesRequest], - Union[ - grafeas.ListOccurrencesResponse, - Awaitable[grafeas.ListOccurrencesResponse] - ]]: - raise NotImplementedError() - - @property - def delete_occurrence(self) -> Callable[ - [grafeas.DeleteOccurrenceRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def create_occurrence(self) -> Callable[ - [grafeas.CreateOccurrenceRequest], - Union[ - grafeas.Occurrence, - Awaitable[grafeas.Occurrence] - ]]: - raise NotImplementedError() - - @property - def batch_create_occurrences(self) -> Callable[ - [grafeas.BatchCreateOccurrencesRequest], - Union[ - grafeas.BatchCreateOccurrencesResponse, - Awaitable[grafeas.BatchCreateOccurrencesResponse] - ]]: - raise NotImplementedError() - - @property - def update_occurrence(self) -> Callable[ - [grafeas.UpdateOccurrenceRequest], - Union[ - grafeas.Occurrence, - Awaitable[grafeas.Occurrence] - ]]: - raise NotImplementedError() - - @property - def get_occurrence_note(self) -> Callable[ - [grafeas.GetOccurrenceNoteRequest], - Union[ - grafeas.Note, - Awaitable[grafeas.Note] - ]]: - raise NotImplementedError() - - @property - def get_note(self) -> Callable[ - [grafeas.GetNoteRequest], - Union[ - grafeas.Note, - Awaitable[grafeas.Note] - ]]: - raise NotImplementedError() - - @property - def list_notes(self) -> Callable[ - [grafeas.ListNotesRequest], - Union[ - grafeas.ListNotesResponse, - Awaitable[grafeas.ListNotesResponse] - ]]: - raise NotImplementedError() - - @property - def delete_note(self) -> Callable[ - [grafeas.DeleteNoteRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def create_note(self) -> Callable[ - [grafeas.CreateNoteRequest], - Union[ - grafeas.Note, - Awaitable[grafeas.Note] - ]]: - raise NotImplementedError() - - @property - def batch_create_notes(self) -> Callable[ - [grafeas.BatchCreateNotesRequest], - Union[ - grafeas.BatchCreateNotesResponse, - Awaitable[grafeas.BatchCreateNotesResponse] - ]]: - raise NotImplementedError() - - @property - def update_note(self) -> Callable[ - [grafeas.UpdateNoteRequest], - Union[ - grafeas.Note, - Awaitable[grafeas.Note] - ]]: - raise NotImplementedError() - - @property - def list_note_occurrences(self) -> Callable[ - [grafeas.ListNoteOccurrencesRequest], - Union[ - grafeas.ListNoteOccurrencesResponse, - Awaitable[grafeas.ListNoteOccurrencesResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'GrafeasTransport', -) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc.py deleted file mode 100644 index 4972ab8..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc.py +++ /dev/null @@ -1,613 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.protobuf import empty_pb2 # type: ignore -from grafeas.grafeas_v1.types import grafeas -from .base import GrafeasTransport, DEFAULT_CLIENT_INFO - - -class GrafeasGrpcTransport(GrafeasTransport): - """gRPC backend transport for Grafeas. - - `Grafeas `__ API. - - Retrieves analysis results of Cloud components such as Docker - container images. - - Analysis results are stored as a series of occurrences. An - ``Occurrence`` contains information about a specific analysis - instance on a resource. An occurrence refers to a ``Note``. A note - contains details describing the analysis and is generally stored in - a separate project, called a ``Provider``. Multiple occurrences can - refer to the same note. - - For example, an SSL vulnerability could affect multiple images. In - this case, there would be one note for the vulnerability and an - occurrence for each image with the vulnerability referring to that - note. - - 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 = 'containeranalysis.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] = {} - - 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 = 'containeranalysis.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 get_occurrence(self) -> Callable[ - [grafeas.GetOccurrenceRequest], - grafeas.Occurrence]: - r"""Return a callable for the get occurrence method over gRPC. - - Gets the specified occurrence. - - Returns: - Callable[[~.GetOccurrenceRequest], - ~.Occurrence]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrence' not in self._stubs: - self._stubs['get_occurrence'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/GetOccurrence', - request_serializer=grafeas.GetOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs['get_occurrence'] - - @property - def list_occurrences(self) -> Callable[ - [grafeas.ListOccurrencesRequest], - grafeas.ListOccurrencesResponse]: - r"""Return a callable for the list occurrences method over gRPC. - - Lists occurrences for the specified project. - - Returns: - Callable[[~.ListOccurrencesRequest], - ~.ListOccurrencesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrences' not in self._stubs: - self._stubs['list_occurrences'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/ListOccurrences', - request_serializer=grafeas.ListOccurrencesRequest.serialize, - response_deserializer=grafeas.ListOccurrencesResponse.deserialize, - ) - return self._stubs['list_occurrences'] - - @property - def delete_occurrence(self) -> Callable[ - [grafeas.DeleteOccurrenceRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete occurrence method over gRPC. - - Deletes the specified occurrence. For example, use - this method to delete an occurrence when the occurrence - is no longer applicable for the given resource. - - Returns: - Callable[[~.DeleteOccurrenceRequest], - ~.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_occurrence' not in self._stubs: - self._stubs['delete_occurrence'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/DeleteOccurrence', - request_serializer=grafeas.DeleteOccurrenceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_occurrence'] - - @property - def create_occurrence(self) -> Callable[ - [grafeas.CreateOccurrenceRequest], - grafeas.Occurrence]: - r"""Return a callable for the create occurrence method over gRPC. - - Creates a new occurrence. - - Returns: - Callable[[~.CreateOccurrenceRequest], - ~.Occurrence]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrence' not in self._stubs: - self._stubs['create_occurrence'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/CreateOccurrence', - request_serializer=grafeas.CreateOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs['create_occurrence'] - - @property - def batch_create_occurrences(self) -> Callable[ - [grafeas.BatchCreateOccurrencesRequest], - grafeas.BatchCreateOccurrencesResponse]: - r"""Return a callable for the batch create occurrences method over gRPC. - - Creates new occurrences in batch. - - Returns: - Callable[[~.BatchCreateOccurrencesRequest], - ~.BatchCreateOccurrencesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_create_occurrences' not in self._stubs: - self._stubs['batch_create_occurrences'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/BatchCreateOccurrences', - request_serializer=grafeas.BatchCreateOccurrencesRequest.serialize, - response_deserializer=grafeas.BatchCreateOccurrencesResponse.deserialize, - ) - return self._stubs['batch_create_occurrences'] - - @property - def update_occurrence(self) -> Callable[ - [grafeas.UpdateOccurrenceRequest], - grafeas.Occurrence]: - r"""Return a callable for the update occurrence method over gRPC. - - Updates the specified occurrence. - - Returns: - Callable[[~.UpdateOccurrenceRequest], - ~.Occurrence]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrence' not in self._stubs: - self._stubs['update_occurrence'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/UpdateOccurrence', - request_serializer=grafeas.UpdateOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs['update_occurrence'] - - @property - def get_occurrence_note(self) -> Callable[ - [grafeas.GetOccurrenceNoteRequest], - grafeas.Note]: - r"""Return a callable for the get occurrence note method over gRPC. - - Gets the note attached to the specified occurrence. - Consumer projects can use this method to get a note that - belongs to a provider project. - - Returns: - Callable[[~.GetOccurrenceNoteRequest], - ~.Note]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrence_note' not in self._stubs: - self._stubs['get_occurrence_note'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/GetOccurrenceNote', - request_serializer=grafeas.GetOccurrenceNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs['get_occurrence_note'] - - @property - def get_note(self) -> Callable[ - [grafeas.GetNoteRequest], - grafeas.Note]: - r"""Return a callable for the get note method over gRPC. - - Gets the specified note. - - Returns: - Callable[[~.GetNoteRequest], - ~.Note]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_note' not in self._stubs: - self._stubs['get_note'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/GetNote', - request_serializer=grafeas.GetNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs['get_note'] - - @property - def list_notes(self) -> Callable[ - [grafeas.ListNotesRequest], - grafeas.ListNotesResponse]: - r"""Return a callable for the list notes method over gRPC. - - Lists notes for the specified project. - - Returns: - Callable[[~.ListNotesRequest], - ~.ListNotesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notes' not in self._stubs: - self._stubs['list_notes'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/ListNotes', - request_serializer=grafeas.ListNotesRequest.serialize, - response_deserializer=grafeas.ListNotesResponse.deserialize, - ) - return self._stubs['list_notes'] - - @property - def delete_note(self) -> Callable[ - [grafeas.DeleteNoteRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete note method over gRPC. - - Deletes the specified note. - - Returns: - Callable[[~.DeleteNoteRequest], - ~.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_note' not in self._stubs: - self._stubs['delete_note'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/DeleteNote', - request_serializer=grafeas.DeleteNoteRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_note'] - - @property - def create_note(self) -> Callable[ - [grafeas.CreateNoteRequest], - grafeas.Note]: - r"""Return a callable for the create note method over gRPC. - - Creates a new note. - - Returns: - Callable[[~.CreateNoteRequest], - ~.Note]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_note' not in self._stubs: - self._stubs['create_note'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/CreateNote', - request_serializer=grafeas.CreateNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs['create_note'] - - @property - def batch_create_notes(self) -> Callable[ - [grafeas.BatchCreateNotesRequest], - grafeas.BatchCreateNotesResponse]: - r"""Return a callable for the batch create notes method over gRPC. - - Creates new notes in batch. - - Returns: - Callable[[~.BatchCreateNotesRequest], - ~.BatchCreateNotesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_create_notes' not in self._stubs: - self._stubs['batch_create_notes'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/BatchCreateNotes', - request_serializer=grafeas.BatchCreateNotesRequest.serialize, - response_deserializer=grafeas.BatchCreateNotesResponse.deserialize, - ) - return self._stubs['batch_create_notes'] - - @property - def update_note(self) -> Callable[ - [grafeas.UpdateNoteRequest], - grafeas.Note]: - r"""Return a callable for the update note method over gRPC. - - Updates the specified note. - - Returns: - Callable[[~.UpdateNoteRequest], - ~.Note]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_note' not in self._stubs: - self._stubs['update_note'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/UpdateNote', - request_serializer=grafeas.UpdateNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs['update_note'] - - @property - def list_note_occurrences(self) -> Callable[ - [grafeas.ListNoteOccurrencesRequest], - grafeas.ListNoteOccurrencesResponse]: - r"""Return a callable for the list note occurrences method over gRPC. - - Lists occurrences referencing the specified note. - Provider projects can use this method to get all - occurrences across consumer projects referencing the - specified note. - - Returns: - Callable[[~.ListNoteOccurrencesRequest], - ~.ListNoteOccurrencesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_note_occurrences' not in self._stubs: - self._stubs['list_note_occurrences'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/ListNoteOccurrences', - request_serializer=grafeas.ListNoteOccurrencesRequest.serialize, - response_deserializer=grafeas.ListNoteOccurrencesResponse.deserialize, - ) - return self._stubs['list_note_occurrences'] - - -__all__ = ( - 'GrafeasGrpcTransport', -) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py b/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py deleted file mode 100644 index 623e8ee..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py +++ /dev/null @@ -1,617 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.protobuf import empty_pb2 # type: ignore -from grafeas.grafeas_v1.types import grafeas -from .base import GrafeasTransport, DEFAULT_CLIENT_INFO -from .grpc import GrafeasGrpcTransport - - -class GrafeasGrpcAsyncIOTransport(GrafeasTransport): - """gRPC AsyncIO backend transport for Grafeas. - - `Grafeas `__ API. - - Retrieves analysis results of Cloud components such as Docker - container images. - - Analysis results are stored as a series of occurrences. An - ``Occurrence`` contains information about a specific analysis - instance on a resource. An occurrence refers to a ``Note``. A note - contains details describing the analysis and is generally stored in - a separate project, called a ``Provider``. Multiple occurrences can - refer to the same note. - - For example, an SSL vulnerability could affect multiple images. In - this case, there would be one note for the vulnerability and an - occurrence for each image with the vulnerability referring to that - note. - - 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 = 'containeranalysis.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 = 'containeranalysis.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] = {} - - 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 get_occurrence(self) -> Callable[ - [grafeas.GetOccurrenceRequest], - Awaitable[grafeas.Occurrence]]: - r"""Return a callable for the get occurrence method over gRPC. - - Gets the specified occurrence. - - Returns: - Callable[[~.GetOccurrenceRequest], - Awaitable[~.Occurrence]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrence' not in self._stubs: - self._stubs['get_occurrence'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/GetOccurrence', - request_serializer=grafeas.GetOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs['get_occurrence'] - - @property - def list_occurrences(self) -> Callable[ - [grafeas.ListOccurrencesRequest], - Awaitable[grafeas.ListOccurrencesResponse]]: - r"""Return a callable for the list occurrences method over gRPC. - - Lists occurrences for the specified project. - - Returns: - Callable[[~.ListOccurrencesRequest], - Awaitable[~.ListOccurrencesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrences' not in self._stubs: - self._stubs['list_occurrences'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/ListOccurrences', - request_serializer=grafeas.ListOccurrencesRequest.serialize, - response_deserializer=grafeas.ListOccurrencesResponse.deserialize, - ) - return self._stubs['list_occurrences'] - - @property - def delete_occurrence(self) -> Callable[ - [grafeas.DeleteOccurrenceRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete occurrence method over gRPC. - - Deletes the specified occurrence. For example, use - this method to delete an occurrence when the occurrence - is no longer applicable for the given resource. - - Returns: - Callable[[~.DeleteOccurrenceRequest], - 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_occurrence' not in self._stubs: - self._stubs['delete_occurrence'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/DeleteOccurrence', - request_serializer=grafeas.DeleteOccurrenceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_occurrence'] - - @property - def create_occurrence(self) -> Callable[ - [grafeas.CreateOccurrenceRequest], - Awaitable[grafeas.Occurrence]]: - r"""Return a callable for the create occurrence method over gRPC. - - Creates a new occurrence. - - Returns: - Callable[[~.CreateOccurrenceRequest], - Awaitable[~.Occurrence]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrence' not in self._stubs: - self._stubs['create_occurrence'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/CreateOccurrence', - request_serializer=grafeas.CreateOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs['create_occurrence'] - - @property - def batch_create_occurrences(self) -> Callable[ - [grafeas.BatchCreateOccurrencesRequest], - Awaitable[grafeas.BatchCreateOccurrencesResponse]]: - r"""Return a callable for the batch create occurrences method over gRPC. - - Creates new occurrences in batch. - - Returns: - Callable[[~.BatchCreateOccurrencesRequest], - Awaitable[~.BatchCreateOccurrencesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_create_occurrences' not in self._stubs: - self._stubs['batch_create_occurrences'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/BatchCreateOccurrences', - request_serializer=grafeas.BatchCreateOccurrencesRequest.serialize, - response_deserializer=grafeas.BatchCreateOccurrencesResponse.deserialize, - ) - return self._stubs['batch_create_occurrences'] - - @property - def update_occurrence(self) -> Callable[ - [grafeas.UpdateOccurrenceRequest], - Awaitable[grafeas.Occurrence]]: - r"""Return a callable for the update occurrence method over gRPC. - - Updates the specified occurrence. - - Returns: - Callable[[~.UpdateOccurrenceRequest], - Awaitable[~.Occurrence]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrence' not in self._stubs: - self._stubs['update_occurrence'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/UpdateOccurrence', - request_serializer=grafeas.UpdateOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs['update_occurrence'] - - @property - def get_occurrence_note(self) -> Callable[ - [grafeas.GetOccurrenceNoteRequest], - Awaitable[grafeas.Note]]: - r"""Return a callable for the get occurrence note method over gRPC. - - Gets the note attached to the specified occurrence. - Consumer projects can use this method to get a note that - belongs to a provider project. - - Returns: - Callable[[~.GetOccurrenceNoteRequest], - Awaitable[~.Note]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_occurrence_note' not in self._stubs: - self._stubs['get_occurrence_note'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/GetOccurrenceNote', - request_serializer=grafeas.GetOccurrenceNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs['get_occurrence_note'] - - @property - def get_note(self) -> Callable[ - [grafeas.GetNoteRequest], - Awaitable[grafeas.Note]]: - r"""Return a callable for the get note method over gRPC. - - Gets the specified note. - - Returns: - Callable[[~.GetNoteRequest], - Awaitable[~.Note]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_note' not in self._stubs: - self._stubs['get_note'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/GetNote', - request_serializer=grafeas.GetNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs['get_note'] - - @property - def list_notes(self) -> Callable[ - [grafeas.ListNotesRequest], - Awaitable[grafeas.ListNotesResponse]]: - r"""Return a callable for the list notes method over gRPC. - - Lists notes for the specified project. - - Returns: - Callable[[~.ListNotesRequest], - Awaitable[~.ListNotesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notes' not in self._stubs: - self._stubs['list_notes'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/ListNotes', - request_serializer=grafeas.ListNotesRequest.serialize, - response_deserializer=grafeas.ListNotesResponse.deserialize, - ) - return self._stubs['list_notes'] - - @property - def delete_note(self) -> Callable[ - [grafeas.DeleteNoteRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete note method over gRPC. - - Deletes the specified note. - - Returns: - Callable[[~.DeleteNoteRequest], - 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_note' not in self._stubs: - self._stubs['delete_note'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/DeleteNote', - request_serializer=grafeas.DeleteNoteRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_note'] - - @property - def create_note(self) -> Callable[ - [grafeas.CreateNoteRequest], - Awaitable[grafeas.Note]]: - r"""Return a callable for the create note method over gRPC. - - Creates a new note. - - Returns: - Callable[[~.CreateNoteRequest], - Awaitable[~.Note]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_note' not in self._stubs: - self._stubs['create_note'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/CreateNote', - request_serializer=grafeas.CreateNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs['create_note'] - - @property - def batch_create_notes(self) -> Callable[ - [grafeas.BatchCreateNotesRequest], - Awaitable[grafeas.BatchCreateNotesResponse]]: - r"""Return a callable for the batch create notes method over gRPC. - - Creates new notes in batch. - - Returns: - Callable[[~.BatchCreateNotesRequest], - Awaitable[~.BatchCreateNotesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_create_notes' not in self._stubs: - self._stubs['batch_create_notes'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/BatchCreateNotes', - request_serializer=grafeas.BatchCreateNotesRequest.serialize, - response_deserializer=grafeas.BatchCreateNotesResponse.deserialize, - ) - return self._stubs['batch_create_notes'] - - @property - def update_note(self) -> Callable[ - [grafeas.UpdateNoteRequest], - Awaitable[grafeas.Note]]: - r"""Return a callable for the update note method over gRPC. - - Updates the specified note. - - Returns: - Callable[[~.UpdateNoteRequest], - Awaitable[~.Note]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_note' not in self._stubs: - self._stubs['update_note'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/UpdateNote', - request_serializer=grafeas.UpdateNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs['update_note'] - - @property - def list_note_occurrences(self) -> Callable[ - [grafeas.ListNoteOccurrencesRequest], - Awaitable[grafeas.ListNoteOccurrencesResponse]]: - r"""Return a callable for the list note occurrences method over gRPC. - - Lists occurrences referencing the specified note. - Provider projects can use this method to get all - occurrences across consumer projects referencing the - specified note. - - Returns: - Callable[[~.ListNoteOccurrencesRequest], - Awaitable[~.ListNoteOccurrencesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_note_occurrences' not in self._stubs: - self._stubs['list_note_occurrences'] = self.grpc_channel.unary_unary( - '/grafeas.v1.Grafeas/ListNoteOccurrences', - request_serializer=grafeas.ListNoteOccurrencesRequest.serialize, - response_deserializer=grafeas.ListNoteOccurrencesResponse.deserialize, - ) - return self._stubs['list_note_occurrences'] - - -__all__ = ( - 'GrafeasGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/__init__.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/__init__.py deleted file mode 100644 index e71985c..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/types/__init__.py +++ /dev/null @@ -1,168 +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 .attestation import ( - AttestationNote, - AttestationOccurrence, -) -from .build import ( - BuildNote, - BuildOccurrence, -) -from .common import ( - RelatedUrl, - Signature, - NoteKind, -) -from .cvss import ( - CVSSv3, -) -from .deployment import ( - DeploymentNote, - DeploymentOccurrence, -) -from .discovery import ( - DiscoveryNote, - DiscoveryOccurrence, -) -from .grafeas import ( - BatchCreateNotesRequest, - BatchCreateNotesResponse, - BatchCreateOccurrencesRequest, - BatchCreateOccurrencesResponse, - CreateNoteRequest, - CreateOccurrenceRequest, - DeleteNoteRequest, - DeleteOccurrenceRequest, - GetNoteRequest, - GetOccurrenceNoteRequest, - GetOccurrenceRequest, - ListNoteOccurrencesRequest, - ListNoteOccurrencesResponse, - ListNotesRequest, - ListNotesResponse, - ListOccurrencesRequest, - ListOccurrencesResponse, - Note, - Occurrence, - UpdateNoteRequest, - UpdateOccurrenceRequest, -) -from .image import ( - Fingerprint, - ImageNote, - ImageOccurrence, - Layer, -) -from .package import ( - Distribution, - Location, - PackageNote, - PackageOccurrence, - Version, - Architecture, -) -from .provenance import ( - AliasContext, - Artifact, - BuildProvenance, - CloudRepoSourceContext, - Command, - FileHashes, - GerritSourceContext, - GitSourceContext, - Hash, - ProjectRepoId, - RepoId, - Source, - SourceContext, -) -from .upgrade import ( - UpgradeDistribution, - UpgradeNote, - UpgradeOccurrence, - WindowsUpdate, -) -from .vulnerability import ( - VulnerabilityNote, - VulnerabilityOccurrence, - Severity, -) - -__all__ = ( - 'AttestationNote', - 'AttestationOccurrence', - 'BuildNote', - 'BuildOccurrence', - 'RelatedUrl', - 'Signature', - 'NoteKind', - 'CVSSv3', - 'DeploymentNote', - 'DeploymentOccurrence', - 'DiscoveryNote', - 'DiscoveryOccurrence', - 'BatchCreateNotesRequest', - 'BatchCreateNotesResponse', - 'BatchCreateOccurrencesRequest', - 'BatchCreateOccurrencesResponse', - 'CreateNoteRequest', - 'CreateOccurrenceRequest', - 'DeleteNoteRequest', - 'DeleteOccurrenceRequest', - 'GetNoteRequest', - 'GetOccurrenceNoteRequest', - 'GetOccurrenceRequest', - 'ListNoteOccurrencesRequest', - 'ListNoteOccurrencesResponse', - 'ListNotesRequest', - 'ListNotesResponse', - 'ListOccurrencesRequest', - 'ListOccurrencesResponse', - 'Note', - 'Occurrence', - 'UpdateNoteRequest', - 'UpdateOccurrenceRequest', - 'Fingerprint', - 'ImageNote', - 'ImageOccurrence', - 'Layer', - 'Distribution', - 'Location', - 'PackageNote', - 'PackageOccurrence', - 'Version', - 'Architecture', - 'AliasContext', - 'Artifact', - 'BuildProvenance', - 'CloudRepoSourceContext', - 'Command', - 'FileHashes', - 'GerritSourceContext', - 'GitSourceContext', - 'Hash', - 'ProjectRepoId', - 'RepoId', - 'Source', - 'SourceContext', - 'UpgradeDistribution', - 'UpgradeNote', - 'UpgradeOccurrence', - 'WindowsUpdate', - 'VulnerabilityNote', - 'VulnerabilityOccurrence', - 'Severity', -) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/attestation.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/attestation.py deleted file mode 100644 index f91538d..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/types/attestation.py +++ /dev/null @@ -1,109 +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 grafeas.grafeas_v1.types import common - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'AttestationNote', - 'AttestationOccurrence', - }, -) - - -class AttestationNote(proto.Message): - r"""Note kind that represents a logical attestation "role" or - "authority". For example, an organization might have one - ``Authority`` for "QA" and one for "build". This note is intended to - act strictly as a grouping mechanism for the attached occurrences - (Attestations). This grouping mechanism also provides a security - boundary, since IAM ACLs gate the ability for a principle to attach - an occurrence to a given note. It also provides a single point of - lookup to find all attached attestation occurrences, even if they - don't all live in the same project. - - Attributes: - hint (grafeas.grafeas_v1.types.AttestationNote.Hint): - Hint hints at the purpose of the attestation - authority. - """ - - class Hint(proto.Message): - r"""This submessage provides human-readable hints about the - purpose of the authority. Because the name of a note acts as its - resource reference, it is important to disambiguate the - canonical name of the Note (which might be a UUID for security - purposes) from "readable" names more suitable for debug output. - Note that these hints should not be used to look up authorities - in security sensitive contexts, such as when looking up - attestations to verify. - - Attributes: - human_readable_name (str): - Required. The human readable name of this - attestation authority, for example "qa". - """ - - human_readable_name = proto.Field( - proto.STRING, - number=1, - ) - - hint = proto.Field( - proto.MESSAGE, - number=1, - message=Hint, - ) - - -class AttestationOccurrence(proto.Message): - r"""Occurrence that represents a single "attestation". The - authenticity of an attestation can be verified using the - attached signature. If the verifier trusts the public key of the - signer, then verifying the signature is sufficient to establish - trust. In this circumstance, the authority to which this - attestation is attached is primarily useful for lookup (how to - find this attestation if you already know the authority and - artifact to be verified) and intent (for which authority this - attestation was intended to sign. - - Attributes: - serialized_payload (bytes): - Required. The serialized payload that is verified by one or - more ``signatures``. - signatures (Sequence[grafeas.grafeas_v1.types.Signature]): - One or more signatures over ``serialized_payload``. Verifier - implementations should consider this attestation message - verified if at least one ``signature`` verifies - ``serialized_payload``. See ``Signature`` in common.proto - for more details on signature structure and verification. - """ - - serialized_payload = proto.Field( - proto.BYTES, - number=1, - ) - signatures = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.Signature, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/build.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/build.py deleted file mode 100644 index d01732f..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/types/build.py +++ /dev/null @@ -1,79 +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 grafeas.grafeas_v1.types import provenance as g_provenance - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'BuildNote', - 'BuildOccurrence', - }, -) - - -class BuildNote(proto.Message): - r"""Note holding the version of the provider's builder and the - signature of the provenance message in the build details - occurrence. - - Attributes: - builder_version (str): - Required. Immutable. Version of the builder - which produced this build. - """ - - builder_version = proto.Field( - proto.STRING, - number=1, - ) - - -class BuildOccurrence(proto.Message): - r"""Details of a build occurrence. - Attributes: - provenance (grafeas.grafeas_v1.types.BuildProvenance): - Required. The actual provenance for the - build. - provenance_bytes (str): - Serialized JSON representation of the provenance, used in - generating the build signature in the corresponding build - note. After verifying the signature, ``provenance_bytes`` - can be unmarshalled and compared to the provenance to - confirm that it is unchanged. A base64-encoded string - representation of the provenance bytes is used for the - signature in order to interoperate with openssl which - expects this format for signature verification. - - The serialized form is captured both to avoid ambiguity in - how the provenance is marshalled to json as well to prevent - incompatibilities with future changes. - """ - - provenance = proto.Field( - proto.MESSAGE, - number=1, - message=g_provenance.BuildProvenance, - ) - provenance_bytes = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/common.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/common.py deleted file mode 100644 index b23e80f..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/types/common.py +++ /dev/null @@ -1,133 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'NoteKind', - 'RelatedUrl', - 'Signature', - }, -) - - -class NoteKind(proto.Enum): - r"""Kind represents the kinds of notes supported.""" - NOTE_KIND_UNSPECIFIED = 0 - VULNERABILITY = 1 - BUILD = 2 - IMAGE = 3 - PACKAGE = 4 - DEPLOYMENT = 5 - DISCOVERY = 6 - ATTESTATION = 7 - UPGRADE = 8 - - -class RelatedUrl(proto.Message): - r"""Metadata for any related URL information. - Attributes: - url (str): - Specific URL associated with the resource. - label (str): - Label to describe usage of the URL. - """ - - url = proto.Field( - proto.STRING, - number=1, - ) - label = proto.Field( - proto.STRING, - number=2, - ) - - -class Signature(proto.Message): - r"""Verifiers (e.g. Kritis implementations) MUST verify signatures with - respect to the trust anchors defined in policy (e.g. a Kritis - policy). Typically this means that the verifier has been configured - with a map from ``public_key_id`` to public key material (and any - required parameters, e.g. signing algorithm). - - In particular, verification implementations MUST NOT treat the - signature ``public_key_id`` as anything more than a key lookup hint. - The ``public_key_id`` DOES NOT validate or authenticate a public - key; it only provides a mechanism for quickly selecting a public key - ALREADY CONFIGURED on the verifier through a trusted channel. - Verification implementations MUST reject signatures in any of the - following circumstances: - - - The ``public_key_id`` is not recognized by the verifier. - - The public key that ``public_key_id`` refers to does not verify - the signature with respect to the payload. - - The ``signature`` contents SHOULD NOT be "attached" (where the - payload is included with the serialized ``signature`` bytes). - Verifiers MUST ignore any "attached" payload and only verify - signatures with respect to explicitly provided payload (e.g. a - ``payload`` field on the proto message that holds this Signature, or - the canonical serialization of the proto message that holds this - signature). - - Attributes: - signature (bytes): - The content of the signature, an opaque - bytestring. The payload that this signature - verifies MUST be unambiguously provided with the - Signature during verification. A wrapper message - might provide the payload explicitly. - Alternatively, a message might have a canonical - serialization that can always be unambiguously - computed to derive the payload. - public_key_id (str): - The identifier for the public key that verifies this - signature. - - - The ``public_key_id`` is required. - - The ``public_key_id`` MUST be an RFC3986 conformant URI. - - When possible, the ``public_key_id`` SHOULD be an - immutable reference, such as a cryptographic digest. - - Examples of valid ``public_key_id``\ s: - - OpenPGP V4 public key fingerprint: - - - "openpgp4fpr:74FAF3B861BDA0870C7B6DEF607E48D2A663AEEA" - See - https://www.iana.org/assignments/uri-schemes/prov/openpgp4fpr - for more details on this scheme. - - RFC6920 digest-named SubjectPublicKeyInfo (digest of the DER - serialization): - - - "ni:///sha-256;cD9o9Cq6LG3jD0iKXqEi_vdjJGecm_iXkbqVoScViaU" - - "nih:///sha-256;703f68f42aba2c6de30f488a5ea122fef76324679c9bf89791ba95a1271589a5". - """ - - signature = proto.Field( - proto.BYTES, - number=1, - ) - public_key_id = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/cvss.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/cvss.py deleted file mode 100644 index 9705a42..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/types/cvss.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'CVSSv3', - }, -) - - -class CVSSv3(proto.Message): - r"""Common Vulnerability Scoring System version 3. - For details, see https://www.first.org/cvss/specification- - document - - Attributes: - base_score (float): - The base score is a function of the base - metric scores. - exploitability_score (float): - - impact_score (float): - - attack_vector (grafeas.grafeas_v1.types.CVSSv3.AttackVector): - Base Metrics - Represents the intrinsic characteristics of a - vulnerability that are constant over time and - across user environments. - attack_complexity (grafeas.grafeas_v1.types.CVSSv3.AttackComplexity): - - privileges_required (grafeas.grafeas_v1.types.CVSSv3.PrivilegesRequired): - - user_interaction (grafeas.grafeas_v1.types.CVSSv3.UserInteraction): - - scope (grafeas.grafeas_v1.types.CVSSv3.Scope): - - confidentiality_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): - - integrity_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): - - availability_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): - - """ - class AttackVector(proto.Enum): - r"""""" - ATTACK_VECTOR_UNSPECIFIED = 0 - ATTACK_VECTOR_NETWORK = 1 - ATTACK_VECTOR_ADJACENT = 2 - ATTACK_VECTOR_LOCAL = 3 - ATTACK_VECTOR_PHYSICAL = 4 - - class AttackComplexity(proto.Enum): - r"""""" - ATTACK_COMPLEXITY_UNSPECIFIED = 0 - ATTACK_COMPLEXITY_LOW = 1 - ATTACK_COMPLEXITY_HIGH = 2 - - class PrivilegesRequired(proto.Enum): - r"""""" - PRIVILEGES_REQUIRED_UNSPECIFIED = 0 - PRIVILEGES_REQUIRED_NONE = 1 - PRIVILEGES_REQUIRED_LOW = 2 - PRIVILEGES_REQUIRED_HIGH = 3 - - class UserInteraction(proto.Enum): - r"""""" - USER_INTERACTION_UNSPECIFIED = 0 - USER_INTERACTION_NONE = 1 - USER_INTERACTION_REQUIRED = 2 - - class Scope(proto.Enum): - r"""""" - SCOPE_UNSPECIFIED = 0 - SCOPE_UNCHANGED = 1 - SCOPE_CHANGED = 2 - - class Impact(proto.Enum): - r"""""" - IMPACT_UNSPECIFIED = 0 - IMPACT_HIGH = 1 - IMPACT_LOW = 2 - IMPACT_NONE = 3 - - base_score = proto.Field( - proto.FLOAT, - number=1, - ) - exploitability_score = proto.Field( - proto.FLOAT, - number=2, - ) - impact_score = proto.Field( - proto.FLOAT, - number=3, - ) - attack_vector = proto.Field( - proto.ENUM, - number=5, - enum=AttackVector, - ) - attack_complexity = proto.Field( - proto.ENUM, - number=6, - enum=AttackComplexity, - ) - privileges_required = proto.Field( - proto.ENUM, - number=7, - enum=PrivilegesRequired, - ) - user_interaction = proto.Field( - proto.ENUM, - number=8, - enum=UserInteraction, - ) - scope = proto.Field( - proto.ENUM, - number=9, - enum=Scope, - ) - confidentiality_impact = proto.Field( - proto.ENUM, - number=10, - enum=Impact, - ) - integrity_impact = proto.Field( - proto.ENUM, - number=11, - enum=Impact, - ) - availability_impact = proto.Field( - proto.ENUM, - number=12, - enum=Impact, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/deployment.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/deployment.py deleted file mode 100644 index 69ac2da..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/types/deployment.py +++ /dev/null @@ -1,109 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'DeploymentNote', - 'DeploymentOccurrence', - }, -) - - -class DeploymentNote(proto.Message): - r"""An artifact that can be deployed in some runtime. - Attributes: - resource_uri (Sequence[str]): - Required. Resource URI for the artifact being - deployed. - """ - - resource_uri = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class DeploymentOccurrence(proto.Message): - r"""The period during which some deployable was active in a - runtime. - - Attributes: - user_email (str): - Identity of the user that triggered this - deployment. - deploy_time (google.protobuf.timestamp_pb2.Timestamp): - Required. Beginning of the lifetime of this - deployment. - undeploy_time (google.protobuf.timestamp_pb2.Timestamp): - End of the lifetime of this deployment. - config (str): - Configuration used to create this deployment. - address (str): - Address of the runtime element hosting this - deployment. - resource_uri (Sequence[str]): - Output only. Resource URI for the artifact - being deployed taken from the deployable field - with the same name. - platform (grafeas.grafeas_v1.types.DeploymentOccurrence.Platform): - Platform hosting this deployment. - """ - class Platform(proto.Enum): - r"""Types of platforms.""" - PLATFORM_UNSPECIFIED = 0 - GKE = 1 - FLEX = 2 - CUSTOM = 3 - - user_email = proto.Field( - proto.STRING, - number=1, - ) - deploy_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - undeploy_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - config = proto.Field( - proto.STRING, - number=4, - ) - address = proto.Field( - proto.STRING, - number=5, - ) - resource_uri = proto.RepeatedField( - proto.STRING, - number=6, - ) - platform = proto.Field( - proto.ENUM, - number=7, - enum=Platform, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/discovery.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/discovery.py deleted file mode 100644 index 9f63dad..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/types/discovery.py +++ /dev/null @@ -1,113 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from grafeas.grafeas_v1.types import common - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'DiscoveryNote', - 'DiscoveryOccurrence', - }, -) - - -class DiscoveryNote(proto.Message): - r"""A note that indicates a type of analysis a provider would perform. - This note exists in a provider's project. A ``Discovery`` occurrence - is created in a consumer's project at the start of analysis. - - Attributes: - analysis_kind (grafeas.grafeas_v1.types.NoteKind): - Required. Immutable. The kind of analysis - that is handled by this discovery. - """ - - analysis_kind = proto.Field( - proto.ENUM, - number=1, - enum=common.NoteKind, - ) - - -class DiscoveryOccurrence(proto.Message): - r"""Provides information about the analysis status of a - discovered resource. - - Attributes: - continuous_analysis (grafeas.grafeas_v1.types.DiscoveryOccurrence.ContinuousAnalysis): - Whether the resource is continuously - analyzed. - analysis_status (grafeas.grafeas_v1.types.DiscoveryOccurrence.AnalysisStatus): - The status of discovery for the resource. - analysis_status_error (google.rpc.status_pb2.Status): - When an error is encountered this will - contain a LocalizedMessage under details to show - to the user. The LocalizedMessage is output only - and populated by the API. - cpe (str): - The CPE of the resource being scanned. - last_scan_time (google.protobuf.timestamp_pb2.Timestamp): - The last time this resource was scanned. - """ - class ContinuousAnalysis(proto.Enum): - r"""Whether the resource is continuously analyzed.""" - CONTINUOUS_ANALYSIS_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - class AnalysisStatus(proto.Enum): - r"""Analysis status for a resource. Currently for initial - analysis only (not updated in continuous analysis). - """ - ANALYSIS_STATUS_UNSPECIFIED = 0 - PENDING = 1 - SCANNING = 2 - FINISHED_SUCCESS = 3 - FINISHED_FAILED = 4 - FINISHED_UNSUPPORTED = 5 - - continuous_analysis = proto.Field( - proto.ENUM, - number=1, - enum=ContinuousAnalysis, - ) - analysis_status = proto.Field( - proto.ENUM, - number=2, - enum=AnalysisStatus, - ) - analysis_status_error = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - cpe = proto.Field( - proto.STRING, - number=4, - ) - last_scan_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/grafeas.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/grafeas.py deleted file mode 100644 index 7a229e7..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/types/grafeas.py +++ /dev/null @@ -1,768 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from grafeas.grafeas_v1.types import attestation as g_attestation -from grafeas.grafeas_v1.types import build as g_build -from grafeas.grafeas_v1.types import common -from grafeas.grafeas_v1.types import deployment as g_deployment -from grafeas.grafeas_v1.types import discovery as g_discovery -from grafeas.grafeas_v1.types import image as g_image -from grafeas.grafeas_v1.types import package as g_package -from grafeas.grafeas_v1.types import upgrade as g_upgrade -from grafeas.grafeas_v1.types import vulnerability as g_vulnerability - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'Occurrence', - 'Note', - 'GetOccurrenceRequest', - 'ListOccurrencesRequest', - 'ListOccurrencesResponse', - 'DeleteOccurrenceRequest', - 'CreateOccurrenceRequest', - 'UpdateOccurrenceRequest', - 'GetNoteRequest', - 'GetOccurrenceNoteRequest', - 'ListNotesRequest', - 'ListNotesResponse', - 'DeleteNoteRequest', - 'CreateNoteRequest', - 'UpdateNoteRequest', - 'ListNoteOccurrencesRequest', - 'ListNoteOccurrencesResponse', - 'BatchCreateNotesRequest', - 'BatchCreateNotesResponse', - 'BatchCreateOccurrencesRequest', - 'BatchCreateOccurrencesResponse', - }, -) - - -class Occurrence(proto.Message): - r"""An instance of an analysis type that has been found on a - resource. - - Attributes: - name (str): - Output only. The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - resource_uri (str): - Required. Immutable. A URI that represents the resource for - which the occurrence applies. For example, - ``https://gcr.io/project/image@sha256:123abc`` for a Docker - image. - note_name (str): - Required. Immutable. The analysis note associated with this - occurrence, in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. This field can - be used as a filter in list requests. - kind (grafeas.grafeas_v1.types.NoteKind): - Output only. This explicitly denotes which of - the occurrence details are specified. This field - can be used as a filter in list requests. - remediation (str): - A description of actions that can be taken to - remedy the note. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this occurrence was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this occurrence was - last updated. - vulnerability (grafeas.grafeas_v1.types.VulnerabilityOccurrence): - Describes a security vulnerability. - build (grafeas.grafeas_v1.types.BuildOccurrence): - Describes a verifiable build. - image (grafeas.grafeas_v1.types.ImageOccurrence): - Describes how this resource derives from the - basis in the associated note. - package (grafeas.grafeas_v1.types.PackageOccurrence): - Describes the installation of a package on - the linked resource. - deployment (grafeas.grafeas_v1.types.DeploymentOccurrence): - Describes the deployment of an artifact on a - runtime. - discovery (grafeas.grafeas_v1.types.DiscoveryOccurrence): - Describes when a resource was discovered. - attestation (grafeas.grafeas_v1.types.AttestationOccurrence): - Describes an attestation of an artifact. - upgrade (grafeas.grafeas_v1.types.UpgradeOccurrence): - Describes an available package upgrade on the - linked resource. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - resource_uri = proto.Field( - proto.STRING, - number=2, - ) - note_name = proto.Field( - proto.STRING, - number=3, - ) - kind = proto.Field( - proto.ENUM, - number=4, - enum=common.NoteKind, - ) - remediation = proto.Field( - proto.STRING, - number=5, - ) - create_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - vulnerability = proto.Field( - proto.MESSAGE, - number=8, - oneof='details', - message=g_vulnerability.VulnerabilityOccurrence, - ) - build = proto.Field( - proto.MESSAGE, - number=9, - oneof='details', - message=g_build.BuildOccurrence, - ) - image = proto.Field( - proto.MESSAGE, - number=10, - oneof='details', - message=g_image.ImageOccurrence, - ) - package = proto.Field( - proto.MESSAGE, - number=11, - oneof='details', - message=g_package.PackageOccurrence, - ) - deployment = proto.Field( - proto.MESSAGE, - number=12, - oneof='details', - message=g_deployment.DeploymentOccurrence, - ) - discovery = proto.Field( - proto.MESSAGE, - number=13, - oneof='details', - message=g_discovery.DiscoveryOccurrence, - ) - attestation = proto.Field( - proto.MESSAGE, - number=14, - oneof='details', - message=g_attestation.AttestationOccurrence, - ) - upgrade = proto.Field( - proto.MESSAGE, - number=15, - oneof='details', - message=g_upgrade.UpgradeOccurrence, - ) - - -class Note(proto.Message): - r"""A type of analysis that can be done for a resource. - Attributes: - name (str): - Output only. The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - short_description (str): - A one sentence description of this note. - long_description (str): - A detailed description of this note. - kind (grafeas.grafeas_v1.types.NoteKind): - Output only. The type of analysis. This field - can be used as a filter in list requests. - related_url (Sequence[grafeas.grafeas_v1.types.RelatedUrl]): - URLs associated with this note. - expiration_time (google.protobuf.timestamp_pb2.Timestamp): - Time of expiration for this note. Empty if - note does not expire. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this note was created. - This field can be used as a filter in list - requests. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this note was last - updated. This field can be used as a filter in - list requests. - related_note_names (Sequence[str]): - Other notes related to this note. - vulnerability (grafeas.grafeas_v1.types.VulnerabilityNote): - A note describing a package vulnerability. - build (grafeas.grafeas_v1.types.BuildNote): - A note describing build provenance for a - verifiable build. - image (grafeas.grafeas_v1.types.ImageNote): - A note describing a base image. - package (grafeas.grafeas_v1.types.PackageNote): - A note describing a package hosted by various - package managers. - deployment (grafeas.grafeas_v1.types.DeploymentNote): - A note describing something that can be - deployed. - discovery (grafeas.grafeas_v1.types.DiscoveryNote): - A note describing the initial analysis of a - resource. - attestation (grafeas.grafeas_v1.types.AttestationNote): - A note describing an attestation role. - upgrade (grafeas.grafeas_v1.types.UpgradeNote): - A note describing available package upgrades. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - short_description = proto.Field( - proto.STRING, - number=2, - ) - long_description = proto.Field( - proto.STRING, - number=3, - ) - kind = proto.Field( - proto.ENUM, - number=4, - enum=common.NoteKind, - ) - related_url = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=common.RelatedUrl, - ) - expiration_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - create_time = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - related_note_names = proto.RepeatedField( - proto.STRING, - number=9, - ) - vulnerability = proto.Field( - proto.MESSAGE, - number=10, - oneof='type', - message=g_vulnerability.VulnerabilityNote, - ) - build = proto.Field( - proto.MESSAGE, - number=11, - oneof='type', - message=g_build.BuildNote, - ) - image = proto.Field( - proto.MESSAGE, - number=12, - oneof='type', - message=g_image.ImageNote, - ) - package = proto.Field( - proto.MESSAGE, - number=13, - oneof='type', - message=g_package.PackageNote, - ) - deployment = proto.Field( - proto.MESSAGE, - number=14, - oneof='type', - message=g_deployment.DeploymentNote, - ) - discovery = proto.Field( - proto.MESSAGE, - number=15, - oneof='type', - message=g_discovery.DiscoveryNote, - ) - attestation = proto.Field( - proto.MESSAGE, - number=16, - oneof='type', - message=g_attestation.AttestationNote, - ) - upgrade = proto.Field( - proto.MESSAGE, - number=17, - oneof='type', - message=g_upgrade.UpgradeNote, - ) - - -class GetOccurrenceRequest(proto.Message): - r"""Request to get an occurrence. - Attributes: - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListOccurrencesRequest(proto.Message): - r"""Request to list occurrences. - Attributes: - parent (str): - The name of the project to list occurrences for in the form - of ``projects/[PROJECT_ID]``. - filter (str): - The filter expression. - page_size (int): - Number of occurrences to return in the list. - Must be positive. Max allowed page size is 1000. - If not specified, page size defaults to 20. - page_token (str): - Token to provide to skip to a particular spot - in the list. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListOccurrencesResponse(proto.Message): - r"""Response for listing occurrences. - Attributes: - occurrences (Sequence[grafeas.grafeas_v1.types.Occurrence]): - The occurrences requested. - next_page_token (str): - The next pagination token in the list response. It should be - used as ``page_token`` for the following request. An empty - value means no more results. - """ - - @property - def raw_page(self): - return self - - occurrences = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Occurrence', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteOccurrenceRequest(proto.Message): - r"""Request to delete an occurrence. - Attributes: - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateOccurrenceRequest(proto.Message): - r"""Request to create a new occurrence. - Attributes: - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrence is to - be created. - occurrence (grafeas.grafeas_v1.types.Occurrence): - The occurrence to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - occurrence = proto.Field( - proto.MESSAGE, - number=2, - message='Occurrence', - ) - - -class UpdateOccurrenceRequest(proto.Message): - r"""Request to update an occurrence. - Attributes: - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - occurrence (grafeas.grafeas_v1.types.Occurrence): - The updated occurrence. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to update. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - occurrence = proto.Field( - proto.MESSAGE, - number=2, - message='Occurrence', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class GetNoteRequest(proto.Message): - r"""Request to get a note. - Attributes: - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetOccurrenceNoteRequest(proto.Message): - r"""Request to get the note to which the specified occurrence is - attached. - - Attributes: - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListNotesRequest(proto.Message): - r"""Request to list notes. - Attributes: - parent (str): - The name of the project to list notes for in the form of - ``projects/[PROJECT_ID]``. - filter (str): - The filter expression. - page_size (int): - Number of notes to return in the list. Must - be positive. Max allowed page size is 1000. If - not specified, page size defaults to 20. - page_token (str): - Token to provide to skip to a particular spot - in the list. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListNotesResponse(proto.Message): - r"""Response for listing notes. - Attributes: - notes (Sequence[grafeas.grafeas_v1.types.Note]): - The notes requested. - next_page_token (str): - The next pagination token in the list response. It should be - used as ``page_token`` for the following request. An empty - value means no more results. - """ - - @property - def raw_page(self): - return self - - notes = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Note', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteNoteRequest(proto.Message): - r"""Request to delete a note. - Attributes: - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateNoteRequest(proto.Message): - r"""Request to create a new note. - Attributes: - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the note is to be - created. - note_id (str): - The ID to use for this note. - note (grafeas.grafeas_v1.types.Note): - The note to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - note_id = proto.Field( - proto.STRING, - number=2, - ) - note = proto.Field( - proto.MESSAGE, - number=3, - message='Note', - ) - - -class UpdateNoteRequest(proto.Message): - r"""Request to update a note. - Attributes: - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - note (grafeas.grafeas_v1.types.Note): - The updated note. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to update. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - note = proto.Field( - proto.MESSAGE, - number=2, - message='Note', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class ListNoteOccurrencesRequest(proto.Message): - r"""Request to list occurrences for a note. - Attributes: - name (str): - The name of the note to list occurrences for in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - filter (str): - The filter expression. - page_size (int): - Number of occurrences to return in the list. - page_token (str): - Token to provide to skip to a particular spot - in the list. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListNoteOccurrencesResponse(proto.Message): - r"""Response for listing occurrences for a note. - Attributes: - occurrences (Sequence[grafeas.grafeas_v1.types.Occurrence]): - The occurrences attached to the specified - note. - next_page_token (str): - Token to provide to skip to a particular spot - in the list. - """ - - @property - def raw_page(self): - return self - - occurrences = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Occurrence', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class BatchCreateNotesRequest(proto.Message): - r"""Request to create notes in batch. - Attributes: - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the notes are to be - created. - notes (Sequence[grafeas.grafeas_v1.types.BatchCreateNotesRequest.NotesEntry]): - The notes to create. Max allowed length is - 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - notes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message='Note', - ) - - -class BatchCreateNotesResponse(proto.Message): - r"""Response for creating notes in batch. - Attributes: - notes (Sequence[grafeas.grafeas_v1.types.Note]): - The notes that were created. - """ - - notes = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Note', - ) - - -class BatchCreateOccurrencesRequest(proto.Message): - r"""Request to create occurrences in batch. - Attributes: - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrences are - to be created. - occurrences (Sequence[grafeas.grafeas_v1.types.Occurrence]): - The occurrences to create. Max allowed length - is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - occurrences = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Occurrence', - ) - - -class BatchCreateOccurrencesResponse(proto.Message): - r"""Response for creating occurrences in batch. - Attributes: - occurrences (Sequence[grafeas.grafeas_v1.types.Occurrence]): - The occurrences that were created. - """ - - occurrences = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Occurrence', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/image.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/image.py deleted file mode 100644 index 3ad287f..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/types/image.py +++ /dev/null @@ -1,153 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'Layer', - 'Fingerprint', - 'ImageNote', - 'ImageOccurrence', - }, -) - - -class Layer(proto.Message): - r"""Layer holds metadata specific to a layer of a Docker image. - Attributes: - directive (str): - Required. The recovered Dockerfile directive - used to construct this layer. See - https://docs.docker.com/engine/reference/builder/ - for more information. - arguments (str): - The recovered arguments to the Dockerfile - directive. - """ - - directive = proto.Field( - proto.STRING, - number=1, - ) - arguments = proto.Field( - proto.STRING, - number=2, - ) - - -class Fingerprint(proto.Message): - r"""A set of properties that uniquely identify a given Docker - image. - - Attributes: - v1_name (str): - Required. The layer ID of the final layer in - the Docker image's v1 representation. - v2_blob (Sequence[str]): - Required. The ordered list of v2 blobs that - represent a given image. - v2_name (str): - Output only. The name of the image's v2 blobs computed via: - [bottom] := v2_blob[bottom] [N] := sha256(v2_blob[N] + " " + - v2_name[N+1]) Only the name of the final blob is kept. - """ - - v1_name = proto.Field( - proto.STRING, - number=1, - ) - v2_blob = proto.RepeatedField( - proto.STRING, - number=2, - ) - v2_name = proto.Field( - proto.STRING, - number=3, - ) - - -class ImageNote(proto.Message): - r"""Basis describes the base image portion (Note) of the DockerImage - relationship. Linked occurrences are derived from this or an - equivalent image via: FROM Or an equivalent - reference, e.g., a tag of the resource_url. - - Attributes: - resource_url (str): - Required. Immutable. The resource_url for the resource - representing the basis of associated occurrence images. - fingerprint (grafeas.grafeas_v1.types.Fingerprint): - Required. Immutable. The fingerprint of the - base image. - """ - - resource_url = proto.Field( - proto.STRING, - number=1, - ) - fingerprint = proto.Field( - proto.MESSAGE, - number=2, - message='Fingerprint', - ) - - -class ImageOccurrence(proto.Message): - r"""Details of the derived image portion of the DockerImage - relationship. This image would be produced from a Dockerfile - with FROM . - - Attributes: - fingerprint (grafeas.grafeas_v1.types.Fingerprint): - Required. The fingerprint of the derived - image. - distance (int): - Output only. The number of layers by which - this image differs from the associated image - basis. - layer_info (Sequence[grafeas.grafeas_v1.types.Layer]): - This contains layer-specific metadata, if populated it has - length "distance" and is ordered with [distance] being the - layer immediately following the base image and [1] being the - final layer. - base_resource_url (str): - Output only. This contains the base image URL - for the derived image occurrence. - """ - - fingerprint = proto.Field( - proto.MESSAGE, - number=1, - message='Fingerprint', - ) - distance = proto.Field( - proto.INT32, - number=2, - ) - layer_info = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Layer', - ) - base_resource_url = proto.Field( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/package.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/package.py deleted file mode 100644 index be72e60..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/types/package.py +++ /dev/null @@ -1,230 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'Architecture', - 'Distribution', - 'Location', - 'PackageNote', - 'PackageOccurrence', - 'Version', - }, -) - - -class Architecture(proto.Enum): - r"""Instruction set architectures supported by various package - managers. - """ - ARCHITECTURE_UNSPECIFIED = 0 - X86 = 1 - X64 = 2 - - -class Distribution(proto.Message): - r"""This represents a particular channel of distribution for a - given package. E.g., Debian's jessie-backports dpkg mirror. - - Attributes: - cpe_uri (str): - Required. The cpe_uri in `CPE - format `__ denoting - the package manager version distributing a package. - architecture (grafeas.grafeas_v1.types.Architecture): - The CPU architecture for which packages in - this distribution channel were built. - latest_version (grafeas.grafeas_v1.types.Version): - The latest available version of this package - in this distribution channel. - maintainer (str): - A freeform string denoting the maintainer of - this package. - url (str): - The distribution channel-specific homepage - for this package. - description (str): - The distribution channel-specific description - of this package. - """ - - cpe_uri = proto.Field( - proto.STRING, - number=1, - ) - architecture = proto.Field( - proto.ENUM, - number=2, - enum='Architecture', - ) - latest_version = proto.Field( - proto.MESSAGE, - number=3, - message='Version', - ) - maintainer = proto.Field( - proto.STRING, - number=4, - ) - url = proto.Field( - proto.STRING, - number=5, - ) - description = proto.Field( - proto.STRING, - number=6, - ) - - -class Location(proto.Message): - r"""An occurrence of a particular package installation found within a - system's filesystem. E.g., glibc was found in - ``/var/lib/dpkg/status``. - - Attributes: - cpe_uri (str): - Required. The CPE URI in `CPE - format `__ denoting - the package manager version distributing a package. - version (grafeas.grafeas_v1.types.Version): - The version installed at this location. - path (str): - The path from which we gathered that this - package/version is installed. - """ - - cpe_uri = proto.Field( - proto.STRING, - number=1, - ) - version = proto.Field( - proto.MESSAGE, - number=2, - message='Version', - ) - path = proto.Field( - proto.STRING, - number=3, - ) - - -class PackageNote(proto.Message): - r"""This represents a particular package that is distributed over - various channels. E.g., glibc (aka libc6) is distributed by - many, at various versions. - - Attributes: - name (str): - Required. Immutable. The name of the package. - distribution (Sequence[grafeas.grafeas_v1.types.Distribution]): - The various channels by which a package is - distributed. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - distribution = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='Distribution', - ) - - -class PackageOccurrence(proto.Message): - r"""Details on how a particular software package was installed on - a system. - - Attributes: - name (str): - Output only. The name of the installed - package. - location (Sequence[grafeas.grafeas_v1.types.Location]): - Required. All of the places within the - filesystem versions of this package have been - found. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - location = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Location', - ) - - -class Version(proto.Message): - r"""Version contains structured information about the version of - a package. - - Attributes: - epoch (int): - Used to correct mistakes in the version - numbering scheme. - name (str): - Required only when version kind is NORMAL. - The main part of the version name. - revision (str): - The iteration of the package build from the - above version. - kind (grafeas.grafeas_v1.types.Version.VersionKind): - Required. Distinguishes between sentinel - MIN/MAX versions and normal versions. - full_name (str): - Human readable version string. This string is - of the form :- and is - only set when kind is NORMAL. - """ - class VersionKind(proto.Enum): - r"""Whether this is an ordinary package version or a sentinel - MIN/MAX version. - """ - VERSION_KIND_UNSPECIFIED = 0 - NORMAL = 1 - MINIMUM = 2 - MAXIMUM = 3 - - epoch = proto.Field( - proto.INT32, - number=1, - ) - name = proto.Field( - proto.STRING, - number=2, - ) - revision = proto.Field( - proto.STRING, - number=3, - ) - kind = proto.Field( - proto.ENUM, - number=4, - enum=VersionKind, - ) - full_name = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/provenance.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/provenance.py deleted file mode 100644 index bb67ca8..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/types/provenance.py +++ /dev/null @@ -1,528 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'BuildProvenance', - 'Source', - 'FileHashes', - 'Hash', - 'Command', - 'Artifact', - 'SourceContext', - 'AliasContext', - 'CloudRepoSourceContext', - 'GerritSourceContext', - 'GitSourceContext', - 'RepoId', - 'ProjectRepoId', - }, -) - - -class BuildProvenance(proto.Message): - r"""Provenance of a build. Contains all information needed to - verify the full details about the build from source to - completion. - - Attributes: - id (str): - Required. Unique identifier of the build. - project_id (str): - ID of the project. - commands (Sequence[grafeas.grafeas_v1.types.Command]): - Commands requested by the build. - built_artifacts (Sequence[grafeas.grafeas_v1.types.Artifact]): - Output of the build. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which the build was created. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which execution of the build was - started. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which execution of the build was - finished. - creator (str): - E-mail address of the user who initiated this - build. Note that this was the user's e-mail - address at the time the build was initiated; - this address may not represent the same end-user - for all time. - logs_uri (str): - URI where any logs for this provenance were - written. - source_provenance (grafeas.grafeas_v1.types.Source): - Details of the Source input to the build. - trigger_id (str): - Trigger identifier if the build was triggered - automatically; empty if not. - build_options (Sequence[grafeas.grafeas_v1.types.BuildProvenance.BuildOptionsEntry]): - Special options applied to this build. This - is a catch-all field where build providers can - enter any desired additional details. - builder_version (str): - Version string of the builder at the time - this build was executed. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - project_id = proto.Field( - proto.STRING, - number=2, - ) - commands = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Command', - ) - built_artifacts = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Artifact', - ) - create_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - start_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - creator = proto.Field( - proto.STRING, - number=8, - ) - logs_uri = proto.Field( - proto.STRING, - number=9, - ) - source_provenance = proto.Field( - proto.MESSAGE, - number=10, - message='Source', - ) - trigger_id = proto.Field( - proto.STRING, - number=11, - ) - build_options = proto.MapField( - proto.STRING, - proto.STRING, - number=12, - ) - builder_version = proto.Field( - proto.STRING, - number=13, - ) - - -class Source(proto.Message): - r"""Source describes the location of the source used for the - build. - - Attributes: - artifact_storage_source_uri (str): - If provided, the input binary artifacts for - the build came from this location. - file_hashes (Sequence[grafeas.grafeas_v1.types.Source.FileHashesEntry]): - Hash(es) of the build source, which can be - used to verify that the original source - integrity was maintained in the build. - 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. - context (grafeas.grafeas_v1.types.SourceContext): - If provided, the source code used for the - build came from this location. - additional_contexts (Sequence[grafeas.grafeas_v1.types.SourceContext]): - If provided, some of the source code used for - the build may be found in these locations, in - the case where the source repository had - multiple remotes or submodules. This list will - not include the context specified in the context - field. - """ - - artifact_storage_source_uri = proto.Field( - proto.STRING, - number=1, - ) - file_hashes = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message='FileHashes', - ) - context = proto.Field( - proto.MESSAGE, - number=3, - message='SourceContext', - ) - additional_contexts = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='SourceContext', - ) - - -class FileHashes(proto.Message): - r"""Container message for hashes of byte content of files, used - in source messages to verify integrity of source input to the - build. - - Attributes: - file_hash (Sequence[grafeas.grafeas_v1.types.Hash]): - Required. 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_ (str): - Required. The type of hash that was - performed, e.g. "SHA-256". - value (bytes): - Required. The hash value. - """ - - type_ = proto.Field( - proto.STRING, - number=1, - ) - value = proto.Field( - proto.BYTES, - number=2, - ) - - -class Command(proto.Message): - r"""Command describes a step performed as part of the build - pipeline. - - Attributes: - name (str): - Required. Name of the command, as presented on the command - line, or if the command is packaged as a Docker container, - as presented to ``docker pull``. - env (Sequence[str]): - Environment variables set before running this - command. - args (Sequence[str]): - Command-line arguments used when executing - this command. - dir_ (str): - Working directory (relative to project source - root) used when running this command. - id (str): - Optional unique identifier for this command, used in - wait_for to reference this command as a dependency. - wait_for (Sequence[str]): - The ID(s) of the command(s) that this command - depends on. - """ - - 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, - ) - - -class Artifact(proto.Message): - r"""Artifact describes a build product. - Attributes: - checksum (str): - Hash or checksum value of a binary, or Docker - Registry 2.0 digest of a container. - id (str): - Artifact ID, if any; for container images, this will be a - URL by digest like - ``gcr.io/projectID/imagename@sha256:123456``. - names (Sequence[str]): - Related artifact names. This may be the path to a binary or - jar file, or in the case of a container build, the name used - to push the container image to Google Container Registry, as - presented to ``docker push``. Note that a single Artifact ID - can have multiple names, for example if two tags are applied - to one image. - """ - - checksum = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - names = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class SourceContext(proto.Message): - r"""A SourceContext is a reference to a tree of files. A - SourceContext together with a path point to a unique revision of - a single file or directory. - - Attributes: - cloud_repo (grafeas.grafeas_v1.types.CloudRepoSourceContext): - A SourceContext referring to a revision in a - Google Cloud Source Repo. - gerrit (grafeas.grafeas_v1.types.GerritSourceContext): - A SourceContext referring to a Gerrit - project. - git (grafeas.grafeas_v1.types.GitSourceContext): - A SourceContext referring to any third party - Git repo (e.g., GitHub). - labels (Sequence[grafeas.grafeas_v1.types.SourceContext.LabelsEntry]): - Labels with user defined metadata. - """ - - cloud_repo = proto.Field( - proto.MESSAGE, - number=1, - oneof='context', - message='CloudRepoSourceContext', - ) - gerrit = proto.Field( - proto.MESSAGE, - number=2, - oneof='context', - message='GerritSourceContext', - ) - git = proto.Field( - proto.MESSAGE, - number=3, - oneof='context', - message='GitSourceContext', - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - - -class AliasContext(proto.Message): - r"""An alias to a repo revision. - Attributes: - kind (grafeas.grafeas_v1.types.AliasContext.Kind): - The alias kind. - name (str): - The alias name. - """ - class Kind(proto.Enum): - r"""The type of an alias.""" - KIND_UNSPECIFIED = 0 - FIXED = 1 - MOVABLE = 2 - OTHER = 4 - - kind = proto.Field( - proto.ENUM, - number=1, - enum=Kind, - ) - name = proto.Field( - proto.STRING, - number=2, - ) - - -class CloudRepoSourceContext(proto.Message): - r"""A CloudRepoSourceContext denotes a particular revision in a - Google Cloud Source Repo. - - Attributes: - repo_id (grafeas.grafeas_v1.types.RepoId): - The ID of the repo. - revision_id (str): - A revision ID. - alias_context (grafeas.grafeas_v1.types.AliasContext): - An alias, which may be a branch or tag. - """ - - repo_id = proto.Field( - proto.MESSAGE, - number=1, - message='RepoId', - ) - revision_id = proto.Field( - proto.STRING, - number=2, - oneof='revision', - ) - alias_context = proto.Field( - proto.MESSAGE, - number=3, - oneof='revision', - message='AliasContext', - ) - - -class GerritSourceContext(proto.Message): - r"""A SourceContext referring to a Gerrit project. - Attributes: - host_uri (str): - The URI of a running Gerrit instance. - gerrit_project (str): - The full project name within the host. - Projects may be nested, so "project/subproject" - is a valid project name. The "repo name" is the - hostURI/project. - revision_id (str): - A revision (commit) ID. - alias_context (grafeas.grafeas_v1.types.AliasContext): - An alias, which may be a branch or tag. - """ - - host_uri = proto.Field( - proto.STRING, - number=1, - ) - gerrit_project = proto.Field( - proto.STRING, - number=2, - ) - revision_id = proto.Field( - proto.STRING, - number=3, - oneof='revision', - ) - alias_context = proto.Field( - proto.MESSAGE, - number=4, - oneof='revision', - message='AliasContext', - ) - - -class GitSourceContext(proto.Message): - r"""A GitSourceContext denotes a particular revision in a third - party Git repository (e.g., GitHub). - - Attributes: - url (str): - Git repository URL. - revision_id (str): - Git commit hash. - """ - - url = proto.Field( - proto.STRING, - number=1, - ) - revision_id = proto.Field( - proto.STRING, - number=2, - ) - - -class RepoId(proto.Message): - r"""A unique identifier for a Cloud Repo. - Attributes: - project_repo_id (grafeas.grafeas_v1.types.ProjectRepoId): - A combination of a project ID and a repo - name. - uid (str): - A server-assigned, globally unique - identifier. - """ - - project_repo_id = proto.Field( - proto.MESSAGE, - number=1, - oneof='id', - message='ProjectRepoId', - ) - uid = proto.Field( - proto.STRING, - number=2, - oneof='id', - ) - - -class ProjectRepoId(proto.Message): - r"""Selects a repo using a Google Cloud Platform project ID - (e.g., winged-cargo-31) and a repo name within that project. - - Attributes: - project_id (str): - The ID of the project. - repo_name (str): - The name of the repo. Leave empty for the - default repo. - """ - - project_id = proto.Field( - proto.STRING, - number=1, - ) - repo_name = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/upgrade.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/upgrade.py deleted file mode 100644 index 31269bc..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/types/upgrade.py +++ /dev/null @@ -1,261 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore -from grafeas.grafeas_v1.types import package as g_package - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'UpgradeNote', - 'UpgradeDistribution', - 'WindowsUpdate', - 'UpgradeOccurrence', - }, -) - - -class UpgradeNote(proto.Message): - r"""An Upgrade Note represents a potential upgrade of a package to a - given version. For each package version combination (i.e. bash 4.0, - bash 4.1, bash 4.1.2), there will be an Upgrade Note. For Windows, - windows_update field represents the information related to the - update. - - Attributes: - package (str): - Required for non-Windows OS. The package this - Upgrade is for. - version (grafeas.grafeas_v1.types.Version): - Required for non-Windows OS. The version of - the package in machine + human readable form. - distributions (Sequence[grafeas.grafeas_v1.types.UpgradeDistribution]): - Metadata about the upgrade for each specific - operating system. - windows_update (grafeas.grafeas_v1.types.WindowsUpdate): - Required for Windows OS. Represents the - metadata about the Windows update. - """ - - package = proto.Field( - proto.STRING, - number=1, - ) - version = proto.Field( - proto.MESSAGE, - number=2, - message=g_package.Version, - ) - distributions = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='UpgradeDistribution', - ) - windows_update = proto.Field( - proto.MESSAGE, - number=4, - message='WindowsUpdate', - ) - - -class UpgradeDistribution(proto.Message): - r"""The Upgrade Distribution represents metadata about the - Upgrade for each operating system (CPE). Some distributions have - additional metadata around updates, classifying them into - various categories and severities. - - Attributes: - cpe_uri (str): - Required - The specific operating system this - metadata applies to. See - https://cpe.mitre.org/specification/. - classification (str): - The operating system classification of this Upgrade, as - specified by the upstream operating system upgrade feed. For - Windows the classification is one of the category_ids listed - at - https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ff357803(v=vs.85) - severity (str): - The severity as specified by the upstream - operating system. - cve (Sequence[str]): - The cve tied to this Upgrade. - """ - - cpe_uri = proto.Field( - proto.STRING, - number=1, - ) - classification = proto.Field( - proto.STRING, - number=2, - ) - severity = proto.Field( - proto.STRING, - number=3, - ) - cve = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -class WindowsUpdate(proto.Message): - r"""Windows Update represents the metadata about the update for - the Windows operating system. The fields in this message come - from the Windows Update API documented at - https://docs.microsoft.com/en-us/windows/win32/api/wuapi/nn- - wuapi-iupdate. - - Attributes: - identity (grafeas.grafeas_v1.types.WindowsUpdate.Identity): - Required - The unique identifier for the - update. - title (str): - The localized title of the update. - description (str): - The localized description of the update. - categories (Sequence[grafeas.grafeas_v1.types.WindowsUpdate.Category]): - The list of categories to which the update - belongs. - kb_article_ids (Sequence[str]): - The Microsoft Knowledge Base article IDs that - are associated with the update. - support_url (str): - The hyperlink to the support information for - the update. - last_published_timestamp (google.protobuf.timestamp_pb2.Timestamp): - The last published timestamp of the update. - """ - - class Identity(proto.Message): - r"""The unique identifier of the update. - Attributes: - update_id (str): - The revision independent identifier of the - update. - revision (int): - The revision number of the update. - """ - - update_id = proto.Field( - proto.STRING, - number=1, - ) - revision = proto.Field( - proto.INT32, - number=2, - ) - - class Category(proto.Message): - r"""The category to which the update belongs. - Attributes: - category_id (str): - The identifier of the category. - name (str): - The localized name of the category. - """ - - category_id = proto.Field( - proto.STRING, - number=1, - ) - name = proto.Field( - proto.STRING, - number=2, - ) - - identity = proto.Field( - proto.MESSAGE, - number=1, - message=Identity, - ) - title = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - categories = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=Category, - ) - kb_article_ids = proto.RepeatedField( - proto.STRING, - number=5, - ) - support_url = proto.Field( - proto.STRING, - number=6, - ) - last_published_timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - - -class UpgradeOccurrence(proto.Message): - r"""An Upgrade Occurrence represents that a specific resource_url could - install a specific upgrade. This presence is supplied via local - sources (i.e. it is present in the mirror and the running system has - noticed its availability). For Windows, both distribution and - windows_update contain information for the Windows update. - - Attributes: - package (str): - Required for non-Windows OS. The package this - Upgrade is for. - parsed_version (grafeas.grafeas_v1.types.Version): - Required for non-Windows OS. The version of - the package in a machine + human readable form. - distribution (grafeas.grafeas_v1.types.UpgradeDistribution): - Metadata about the upgrade for available for the specific - operating system for the resource_url. This allows efficient - filtering, as well as making it easier to use the - occurrence. - windows_update (grafeas.grafeas_v1.types.WindowsUpdate): - Required for Windows OS. Represents the - metadata about the Windows update. - """ - - package = proto.Field( - proto.STRING, - number=1, - ) - parsed_version = proto.Field( - proto.MESSAGE, - number=3, - message=g_package.Version, - ) - distribution = proto.Field( - proto.MESSAGE, - number=4, - message='UpgradeDistribution', - ) - windows_update = proto.Field( - proto.MESSAGE, - number=5, - message='WindowsUpdate', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/grafeas/grafeas_v1/types/vulnerability.py b/owl-bot-staging/v1/grafeas/grafeas_v1/types/vulnerability.py deleted file mode 100644 index 380d915..0000000 --- a/owl-bot-staging/v1/grafeas/grafeas_v1/types/vulnerability.py +++ /dev/null @@ -1,424 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore -from grafeas.grafeas_v1.types import common -from grafeas.grafeas_v1.types import cvss -from grafeas.grafeas_v1.types import package - - -__protobuf__ = proto.module( - package='grafeas.v1', - manifest={ - 'Severity', - 'VulnerabilityNote', - 'VulnerabilityOccurrence', - }, -) - - -class Severity(proto.Enum): - r"""Note provider assigned severity/impact ranking.""" - SEVERITY_UNSPECIFIED = 0 - MINIMAL = 1 - LOW = 2 - MEDIUM = 3 - HIGH = 4 - CRITICAL = 5 - - -class VulnerabilityNote(proto.Message): - r"""A security vulnerability that can be found in resources. - Attributes: - cvss_score (float): - The CVSS score of this vulnerability. CVSS - score is on a scale of 0 - 10 where 0 indicates - low severity and 10 indicates high severity. - severity (grafeas.grafeas_v1.types.Severity): - The note provider assigned severity of this - vulnerability. - details (Sequence[grafeas.grafeas_v1.types.VulnerabilityNote.Detail]): - Details of all known distros and packages - affected by this vulnerability. - cvss_v3 (grafeas.grafeas_v1.types.CVSSv3): - The full description of the CVSSv3 for this - vulnerability. - windows_details (Sequence[grafeas.grafeas_v1.types.VulnerabilityNote.WindowsDetail]): - Windows details get their own format because - the information format and model don't match a - normal detail. Specifically Windows updates are - done as patches, thus Windows vulnerabilities - really are a missing package, rather than a - package being at an incorrect version. - source_update_time (google.protobuf.timestamp_pb2.Timestamp): - The time this information was last changed at - the source. This is an upstream timestamp from - the underlying information source - e.g. Ubuntu - security tracker. - """ - - class Detail(proto.Message): - r"""A detail for a distro and package affected by this - vulnerability and its associated fix (if one is available). - - Attributes: - severity_name (str): - The distro assigned severity of this - vulnerability. - description (str): - A vendor-specific description of this - vulnerability. - package_type (str): - The type of package; whether native or non - native (e.g., ruby gems, node.js packages, - etc.). - affected_cpe_uri (str): - Required. The `CPE - URI `__ this - vulnerability affects. - affected_package (str): - Required. The package this vulnerability - affects. - affected_version_start (grafeas.grafeas_v1.types.Version): - The version number at the start of an interval in which this - vulnerability exists. A vulnerability can affect a package - between version numbers that are disjoint sets of intervals - (example: [1.0.0-1.1.0], [2.4.6-2.4.8] and [4.5.6-4.6.8]) - each of which will be represented in its own Detail. If a - specific affected version is provided by a vulnerability - database, affected_version_start and affected_version_end - will be the same in that Detail. - affected_version_end (grafeas.grafeas_v1.types.Version): - The version number at the end of an interval in which this - vulnerability exists. A vulnerability can affect a package - between version numbers that are disjoint sets of intervals - (example: [1.0.0-1.1.0], [2.4.6-2.4.8] and [4.5.6-4.6.8]) - each of which will be represented in its own Detail. If a - specific affected version is provided by a vulnerability - database, affected_version_start and affected_version_end - will be the same in that Detail. - fixed_cpe_uri (str): - The distro recommended `CPE - URI `__ to update to - that contains a fix for this vulnerability. It is possible - for this to be different from the affected_cpe_uri. - fixed_package (str): - The distro recommended package to update to that contains a - fix for this vulnerability. It is possible for this to be - different from the affected_package. - fixed_version (grafeas.grafeas_v1.types.Version): - The distro recommended version to update to - that contains a fix for this vulnerability. - Setting this to VersionKind.MAXIMUM means no - such version is yet available. - is_obsolete (bool): - Whether this detail is obsolete. Occurrences - are expected not to point to obsolete details. - source_update_time (google.protobuf.timestamp_pb2.Timestamp): - The time this information was last changed at - the source. This is an upstream timestamp from - the underlying information source - e.g. Ubuntu - security tracker. - """ - - severity_name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - package_type = proto.Field( - proto.STRING, - number=3, - ) - affected_cpe_uri = proto.Field( - proto.STRING, - number=4, - ) - affected_package = proto.Field( - proto.STRING, - number=5, - ) - affected_version_start = proto.Field( - proto.MESSAGE, - number=6, - message=package.Version, - ) - affected_version_end = proto.Field( - proto.MESSAGE, - number=7, - message=package.Version, - ) - fixed_cpe_uri = proto.Field( - proto.STRING, - number=8, - ) - fixed_package = proto.Field( - proto.STRING, - number=9, - ) - fixed_version = proto.Field( - proto.MESSAGE, - number=10, - message=package.Version, - ) - is_obsolete = proto.Field( - proto.BOOL, - number=11, - ) - source_update_time = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - - class WindowsDetail(proto.Message): - r""" - Attributes: - cpe_uri (str): - Required. The `CPE - URI `__ this - vulnerability affects. - name (str): - Required. The name of this vulnerability. - description (str): - The description of this vulnerability. - fixing_kbs (Sequence[grafeas.grafeas_v1.types.VulnerabilityNote.WindowsDetail.KnowledgeBase]): - Required. The names of the KBs which have - hotfixes to mitigate this vulnerability. Note - that there may be multiple hotfixes (and thus - multiple KBs) that mitigate a given - vulnerability. Currently any listed KBs presence - is considered a fix. - """ - - class KnowledgeBase(proto.Message): - r""" - Attributes: - name (str): - The KB name (generally of the form KB[0-9]+ (e.g., - KB123456)). - url (str): - A link to the KB in the [Windows update catalog] - (https://www.catalog.update.microsoft.com/). - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - url = proto.Field( - proto.STRING, - number=2, - ) - - cpe_uri = proto.Field( - proto.STRING, - number=1, - ) - name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - fixing_kbs = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='VulnerabilityNote.WindowsDetail.KnowledgeBase', - ) - - cvss_score = proto.Field( - proto.FLOAT, - number=1, - ) - severity = proto.Field( - proto.ENUM, - number=2, - enum='Severity', - ) - details = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=Detail, - ) - cvss_v3 = proto.Field( - proto.MESSAGE, - number=4, - message=cvss.CVSSv3, - ) - windows_details = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=WindowsDetail, - ) - source_update_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - -class VulnerabilityOccurrence(proto.Message): - r"""An occurrence of a severity vulnerability on a resource. - Attributes: - type_ (str): - The type of package; whether native or non - native (e.g., ruby gems, node.js packages, - etc.). - severity (grafeas.grafeas_v1.types.Severity): - Output only. The note provider assigned - severity of this vulnerability. - cvss_score (float): - Output only. The CVSS score of this - vulnerability. CVSS score is on a scale of 0 - - 10 where 0 indicates low severity and 10 - indicates high severity. - package_issue (Sequence[grafeas.grafeas_v1.types.VulnerabilityOccurrence.PackageIssue]): - Required. The set of affected locations and - their fixes (if available) within the associated - resource. - short_description (str): - Output only. A one sentence description of - this vulnerability. - long_description (str): - Output only. A detailed description of this - vulnerability. - related_urls (Sequence[grafeas.grafeas_v1.types.RelatedUrl]): - Output only. URLs related to this - vulnerability. - effective_severity (grafeas.grafeas_v1.types.Severity): - The distro assigned severity for this - vulnerability when it is available, otherwise - this is the note provider assigned severity. - fix_available (bool): - Output only. Whether at least one of the - affected packages has a fix available. - """ - - class PackageIssue(proto.Message): - r"""A detail for a distro and package this vulnerability - occurrence was found in and its associated fix (if one is - available). - - Attributes: - affected_cpe_uri (str): - Required. The `CPE - URI `__ this - vulnerability was found in. - affected_package (str): - Required. The package this vulnerability was - found in. - affected_version (grafeas.grafeas_v1.types.Version): - Required. The version of the package that is - installed on the resource affected by this - vulnerability. - fixed_cpe_uri (str): - The `CPE URI `__ this - vulnerability was fixed in. It is possible for this to be - different from the affected_cpe_uri. - fixed_package (str): - The package this vulnerability was fixed in. It is possible - for this to be different from the affected_package. - fixed_version (grafeas.grafeas_v1.types.Version): - Required. The version of the package this - vulnerability was fixed in. Setting this to - VersionKind.MAXIMUM means no fix is yet - available. - fix_available (bool): - Output only. Whether a fix is available for - this package. - """ - - affected_cpe_uri = proto.Field( - proto.STRING, - number=1, - ) - affected_package = proto.Field( - proto.STRING, - number=2, - ) - affected_version = proto.Field( - proto.MESSAGE, - number=3, - message=package.Version, - ) - fixed_cpe_uri = proto.Field( - proto.STRING, - number=4, - ) - fixed_package = proto.Field( - proto.STRING, - number=5, - ) - fixed_version = proto.Field( - proto.MESSAGE, - number=6, - message=package.Version, - ) - fix_available = proto.Field( - proto.BOOL, - number=7, - ) - - type_ = proto.Field( - proto.STRING, - number=1, - ) - severity = proto.Field( - proto.ENUM, - number=2, - enum='Severity', - ) - cvss_score = proto.Field( - proto.FLOAT, - number=3, - ) - package_issue = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=PackageIssue, - ) - short_description = proto.Field( - proto.STRING, - number=5, - ) - long_description = proto.Field( - proto.STRING, - number=6, - ) - related_urls = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=common.RelatedUrl, - ) - effective_severity = proto.Field( - proto.ENUM, - number=8, - enum='Severity', - ) - fix_available = proto.Field( - proto.BOOL, - number=9, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 4505b48..0000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index c01f245..0000000 --- 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=grafeas/grafeas_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', - 'grafeas', - ) - - -@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_grafeas_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_grafeas_v1_keywords.py deleted file mode 100644 index f8eaf65..0000000 --- a/owl-bot-staging/v1/scripts/fixup_grafeas_v1_keywords.py +++ /dev/null @@ -1,189 +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 grafeasCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_create_notes': ('parent', 'notes', ), - 'batch_create_occurrences': ('parent', 'occurrences', ), - 'create_note': ('parent', 'note_id', 'note', ), - 'create_occurrence': ('parent', 'occurrence', ), - 'delete_note': ('name', ), - 'delete_occurrence': ('name', ), - 'get_note': ('name', ), - 'get_occurrence': ('name', ), - 'get_occurrence_note': ('name', ), - 'list_note_occurrences': ('name', 'filter', 'page_size', 'page_token', ), - 'list_notes': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_occurrences': ('parent', 'filter', 'page_size', 'page_token', ), - 'update_note': ('name', 'note', 'update_mask', ), - 'update_occurrence': ('name', 'occurrence', 'update_mask', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: 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=grafeasCallTransformer(), -): - """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 grafeas 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 3b22890..0000000 --- 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='grafeas-grafeas', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('grafeas',), - 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 b54a5fc..0000000 --- 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 b54a5fc..0000000 --- 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 b54a5fc..0000000 --- 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/grafeas_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/grafeas_v1/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/grafeas_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/grafeas_v1/test_grafeas.py b/owl-bot-staging/v1/tests/unit/gapic/grafeas_v1/test_grafeas.py deleted file mode 100644 index 35fa33e..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/grafeas_v1/test_grafeas.py +++ /dev/null @@ -1,4957 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from grafeas.grafeas_v1.services.grafeas import GrafeasAsyncClient -from grafeas.grafeas_v1.services.grafeas import GrafeasClient -from grafeas.grafeas_v1.services.grafeas import pagers -from grafeas.grafeas_v1.services.grafeas import transports -from grafeas.grafeas_v1.services.grafeas.transports.base import _GOOGLE_AUTH_VERSION -from grafeas.grafeas_v1.types import attestation -from grafeas.grafeas_v1.types import build -from grafeas.grafeas_v1.types import common -from grafeas.grafeas_v1.types import cvss -from grafeas.grafeas_v1.types import deployment -from grafeas.grafeas_v1.types import discovery -from grafeas.grafeas_v1.types import grafeas -from grafeas.grafeas_v1.types import image -from grafeas.grafeas_v1.types import package -from grafeas.grafeas_v1.types import provenance -from grafeas.grafeas_v1.types import upgrade -from grafeas.grafeas_v1.types import vulnerability -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 GrafeasClient._get_default_mtls_endpoint(None) is None - assert GrafeasClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert GrafeasClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert GrafeasClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert GrafeasClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert GrafeasClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - GrafeasClient, - GrafeasAsyncClient, -]) -def test_grafeas_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 == 'containeranalysis.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.GrafeasGrpcTransport, "grpc"), - (transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_grafeas_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", [ - GrafeasClient, - GrafeasAsyncClient, -]) -def test_grafeas_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 == 'containeranalysis.googleapis.com:443' - - -def test_grafeas_client_get_transport_class(): - transport = GrafeasClient.get_transport_class() - available_transports = [ - transports.GrafeasGrpcTransport, - ] - assert transport in available_transports - - transport = GrafeasClient.get_transport_class("grpc") - assert transport == transports.GrafeasGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (GrafeasClient, transports.GrafeasGrpcTransport, "grpc"), - (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(GrafeasClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GrafeasClient)) -@mock.patch.object(GrafeasAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GrafeasAsyncClient)) -def test_grafeas_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(GrafeasClient, '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(GrafeasClient, '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", [ - (GrafeasClient, transports.GrafeasGrpcTransport, "grpc", "true"), - (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (GrafeasClient, transports.GrafeasGrpcTransport, "grpc", "false"), - (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(GrafeasClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GrafeasClient)) -@mock.patch.object(GrafeasAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GrafeasAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_grafeas_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", [ - (GrafeasClient, transports.GrafeasGrpcTransport, "grpc"), - (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_grafeas_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", [ - (GrafeasClient, transports.GrafeasGrpcTransport, "grpc"), - (GrafeasAsyncClient, transports.GrafeasGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_grafeas_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_grafeas_client_client_options_from_dict(): - with mock.patch('grafeas.grafeas_v1.services.grafeas.transports.GrafeasGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = GrafeasClient( - 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_get_occurrence(transport: str = 'grpc', request_type=grafeas.GetOccurrenceRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_value', - vulnerability=vulnerability.VulnerabilityOccurrence(type_='type__value'), - ) - response = client.get_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.GetOccurrenceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == 'name_value' - assert response.resource_uri == 'resource_uri_value' - assert response.note_name == 'note_name_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == 'remediation_value' - - -def test_get_occurrence_from_dict(): - test_get_occurrence(request_type=dict) - - -def test_get_occurrence_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 = GrafeasClient( - 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_occurrence), - '__call__') as call: - client.get_occurrence() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.GetOccurrenceRequest() - - -@pytest.mark.asyncio -async def test_get_occurrence_async(transport: str = 'grpc_asyncio', request_type=grafeas.GetOccurrenceRequest): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_value', - )) - response = await client.get_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.GetOccurrenceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == 'name_value' - assert response.resource_uri == 'resource_uri_value' - assert response.note_name == 'note_name_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == 'remediation_value' - - -@pytest.mark.asyncio -async def test_get_occurrence_async_from_dict(): - await test_get_occurrence_async(request_type=dict) - - -def test_get_occurrence_field_headers(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.GetOccurrenceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence), - '__call__') as call: - call.return_value = grafeas.Occurrence() - client.get_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_occurrence_field_headers_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.GetOccurrenceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - await client.get_occurrence(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_occurrence_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_occurrence( - 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_occurrence_flattened_error(): - client = GrafeasClient( - 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_occurrence( - grafeas.GetOccurrenceRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_occurrence_flattened_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_occurrence( - 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_occurrence_flattened_error_async(): - client = GrafeasAsyncClient( - 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_occurrence( - grafeas.GetOccurrenceRequest(), - name='name_value', - ) - - -def test_list_occurrences(transport: str = 'grpc', request_type=grafeas.ListOccurrencesRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListOccurrencesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.ListOccurrencesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOccurrencesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_occurrences_from_dict(): - test_list_occurrences(request_type=dict) - - -def test_list_occurrences_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 = GrafeasClient( - 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_occurrences), - '__call__') as call: - client.list_occurrences() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.ListOccurrencesRequest() - - -@pytest.mark.asyncio -async def test_list_occurrences_async(transport: str = 'grpc_asyncio', request_type=grafeas.ListOccurrencesRequest): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListOccurrencesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.ListOccurrencesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOccurrencesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_occurrences_async_from_dict(): - await test_list_occurrences_async(request_type=dict) - - -def test_list_occurrences_field_headers(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.ListOccurrencesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__') as call: - call.return_value = grafeas.ListOccurrencesResponse() - client.list_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_occurrences_field_headers_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.ListOccurrencesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListOccurrencesResponse()) - await client.list_occurrences(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_occurrences_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListOccurrencesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_occurrences( - parent='parent_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].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -def test_list_occurrences_flattened_error(): - client = GrafeasClient( - 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_occurrences( - grafeas.ListOccurrencesRequest(), - parent='parent_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_list_occurrences_flattened_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListOccurrencesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListOccurrencesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_occurrences( - parent='parent_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].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_list_occurrences_flattened_error_async(): - client = GrafeasAsyncClient( - 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_occurrences( - grafeas.ListOccurrencesRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_occurrences_pager(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_occurrences(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, grafeas.Occurrence) - for i in results) - -def test_list_occurrences_pages(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - pages = list(client.list_occurrences(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_occurrences_async_pager(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_occurrences(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, grafeas.Occurrence) - for i in responses) - -@pytest.mark.asyncio -async def test_list_occurrences_async_pages(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_occurrences(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_occurrence(transport: str = 'grpc', request_type=grafeas.DeleteOccurrenceRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.DeleteOccurrenceRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_occurrence_from_dict(): - test_delete_occurrence(request_type=dict) - - -def test_delete_occurrence_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 = GrafeasClient( - 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_occurrence), - '__call__') as call: - client.delete_occurrence() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.DeleteOccurrenceRequest() - - -@pytest.mark.asyncio -async def test_delete_occurrence_async(transport: str = 'grpc_asyncio', request_type=grafeas.DeleteOccurrenceRequest): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.DeleteOccurrenceRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_occurrence_async_from_dict(): - await test_delete_occurrence_async(request_type=dict) - - -def test_delete_occurrence_field_headers(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.DeleteOccurrenceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), - '__call__') as call: - call.return_value = None - client.delete_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_occurrence_field_headers_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.DeleteOccurrenceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_occurrence(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_occurrence_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), - '__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_occurrence( - 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_occurrence_flattened_error(): - client = GrafeasClient( - 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_occurrence( - grafeas.DeleteOccurrenceRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_occurrence_flattened_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), - '__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_occurrence( - 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_occurrence_flattened_error_async(): - client = GrafeasAsyncClient( - 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_occurrence( - grafeas.DeleteOccurrenceRequest(), - name='name_value', - ) - - -def test_create_occurrence(transport: str = 'grpc', request_type=grafeas.CreateOccurrenceRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_value', - vulnerability=vulnerability.VulnerabilityOccurrence(type_='type__value'), - ) - response = client.create_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.CreateOccurrenceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == 'name_value' - assert response.resource_uri == 'resource_uri_value' - assert response.note_name == 'note_name_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == 'remediation_value' - - -def test_create_occurrence_from_dict(): - test_create_occurrence(request_type=dict) - - -def test_create_occurrence_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 = GrafeasClient( - 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_occurrence), - '__call__') as call: - client.create_occurrence() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.CreateOccurrenceRequest() - - -@pytest.mark.asyncio -async def test_create_occurrence_async(transport: str = 'grpc_asyncio', request_type=grafeas.CreateOccurrenceRequest): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_value', - )) - response = await client.create_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.CreateOccurrenceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == 'name_value' - assert response.resource_uri == 'resource_uri_value' - assert response.note_name == 'note_name_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == 'remediation_value' - - -@pytest.mark.asyncio -async def test_create_occurrence_async_from_dict(): - await test_create_occurrence_async(request_type=dict) - - -def test_create_occurrence_field_headers(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.CreateOccurrenceRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), - '__call__') as call: - call.return_value = grafeas.Occurrence() - client.create_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_occurrence_field_headers_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.CreateOccurrenceRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - await client.create_occurrence(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_occurrence_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_occurrence( - parent='parent_value', - occurrence=grafeas.Occurrence(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].parent == 'parent_value' - assert args[0].occurrence == grafeas.Occurrence(name='name_value') - - -def test_create_occurrence_flattened_error(): - client = GrafeasClient( - 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_occurrence( - grafeas.CreateOccurrenceRequest(), - parent='parent_value', - occurrence=grafeas.Occurrence(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_occurrence_flattened_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_occurrence( - parent='parent_value', - occurrence=grafeas.Occurrence(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].parent == 'parent_value' - assert args[0].occurrence == grafeas.Occurrence(name='name_value') - - -@pytest.mark.asyncio -async def test_create_occurrence_flattened_error_async(): - client = GrafeasAsyncClient( - 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_occurrence( - grafeas.CreateOccurrenceRequest(), - parent='parent_value', - occurrence=grafeas.Occurrence(name='name_value'), - ) - - -def test_batch_create_occurrences(transport: str = 'grpc', request_type=grafeas.BatchCreateOccurrencesRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateOccurrencesResponse( - ) - response = client.batch_create_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.BatchCreateOccurrencesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.BatchCreateOccurrencesResponse) - - -def test_batch_create_occurrences_from_dict(): - test_batch_create_occurrences(request_type=dict) - - -def test_batch_create_occurrences_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 = GrafeasClient( - 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.batch_create_occurrences), - '__call__') as call: - client.batch_create_occurrences() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.BatchCreateOccurrencesRequest() - - -@pytest.mark.asyncio -async def test_batch_create_occurrences_async(transport: str = 'grpc_asyncio', request_type=grafeas.BatchCreateOccurrencesRequest): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateOccurrencesResponse( - )) - response = await client.batch_create_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.BatchCreateOccurrencesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.BatchCreateOccurrencesResponse) - - -@pytest.mark.asyncio -async def test_batch_create_occurrences_async_from_dict(): - await test_batch_create_occurrences_async(request_type=dict) - - -def test_batch_create_occurrences_field_headers(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.BatchCreateOccurrencesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), - '__call__') as call: - call.return_value = grafeas.BatchCreateOccurrencesResponse() - client.batch_create_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_batch_create_occurrences_field_headers_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.BatchCreateOccurrencesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateOccurrencesResponse()) - await client.batch_create_occurrences(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_batch_create_occurrences_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateOccurrencesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.batch_create_occurrences( - parent='parent_value', - occurrences=[grafeas.Occurrence(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].parent == 'parent_value' - assert args[0].occurrences == [grafeas.Occurrence(name='name_value')] - - -def test_batch_create_occurrences_flattened_error(): - client = GrafeasClient( - 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.batch_create_occurrences( - grafeas.BatchCreateOccurrencesRequest(), - parent='parent_value', - occurrences=[grafeas.Occurrence(name='name_value')], - ) - - -@pytest.mark.asyncio -async def test_batch_create_occurrences_flattened_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateOccurrencesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateOccurrencesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_create_occurrences( - parent='parent_value', - occurrences=[grafeas.Occurrence(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].parent == 'parent_value' - assert args[0].occurrences == [grafeas.Occurrence(name='name_value')] - - -@pytest.mark.asyncio -async def test_batch_create_occurrences_flattened_error_async(): - client = GrafeasAsyncClient( - 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.batch_create_occurrences( - grafeas.BatchCreateOccurrencesRequest(), - parent='parent_value', - occurrences=[grafeas.Occurrence(name='name_value')], - ) - - -def test_update_occurrence(transport: str = 'grpc', request_type=grafeas.UpdateOccurrenceRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_value', - vulnerability=vulnerability.VulnerabilityOccurrence(type_='type__value'), - ) - response = client.update_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.UpdateOccurrenceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == 'name_value' - assert response.resource_uri == 'resource_uri_value' - assert response.note_name == 'note_name_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == 'remediation_value' - - -def test_update_occurrence_from_dict(): - test_update_occurrence(request_type=dict) - - -def test_update_occurrence_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 = GrafeasClient( - 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_occurrence), - '__call__') as call: - client.update_occurrence() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.UpdateOccurrenceRequest() - - -@pytest.mark.asyncio -async def test_update_occurrence_async(transport: str = 'grpc_asyncio', request_type=grafeas.UpdateOccurrenceRequest): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence( - name='name_value', - resource_uri='resource_uri_value', - note_name='note_name_value', - kind=common.NoteKind.VULNERABILITY, - remediation='remediation_value', - )) - response = await client.update_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.UpdateOccurrenceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == 'name_value' - assert response.resource_uri == 'resource_uri_value' - assert response.note_name == 'note_name_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == 'remediation_value' - - -@pytest.mark.asyncio -async def test_update_occurrence_async_from_dict(): - await test_update_occurrence_async(request_type=dict) - - -def test_update_occurrence_field_headers(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.UpdateOccurrenceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), - '__call__') as call: - call.return_value = grafeas.Occurrence() - client.update_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_update_occurrence_field_headers_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.UpdateOccurrenceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - await client.update_occurrence(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_update_occurrence_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_occurrence( - name='name_value', - occurrence=grafeas.Occurrence(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].name == 'name_value' - assert args[0].occurrence == grafeas.Occurrence(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_occurrence_flattened_error(): - client = GrafeasClient( - 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_occurrence( - grafeas.UpdateOccurrenceRequest(), - name='name_value', - occurrence=grafeas.Occurrence(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_occurrence_flattened_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_occurrence( - name='name_value', - occurrence=grafeas.Occurrence(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].name == 'name_value' - assert args[0].occurrence == grafeas.Occurrence(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_occurrence_flattened_error_async(): - client = GrafeasAsyncClient( - 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_occurrence( - grafeas.UpdateOccurrenceRequest(), - name='name_value', - occurrence=grafeas.Occurrence(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_occurrence_note(transport: str = 'grpc', request_type=grafeas.GetOccurrenceNoteRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_occurrence_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - vulnerability=vulnerability.VulnerabilityNote(cvss_score=0.1082), - ) - response = client.get_occurrence_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.GetOccurrenceNoteRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -def test_get_occurrence_note_from_dict(): - test_get_occurrence_note(request_type=dict) - - -def test_get_occurrence_note_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 = GrafeasClient( - 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_occurrence_note), - '__call__') as call: - client.get_occurrence_note() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.GetOccurrenceNoteRequest() - - -@pytest.mark.asyncio -async def test_get_occurrence_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.GetOccurrenceNoteRequest): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_occurrence_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - )) - response = await client.get_occurrence_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.GetOccurrenceNoteRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -@pytest.mark.asyncio -async def test_get_occurrence_note_async_from_dict(): - await test_get_occurrence_note_async(request_type=dict) - - -def test_get_occurrence_note_field_headers(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.GetOccurrenceNoteRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), - '__call__') as call: - call.return_value = grafeas.Note() - client.get_occurrence_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_occurrence_note_field_headers_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.GetOccurrenceNoteRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - await client.get_occurrence_note(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_occurrence_note_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_occurrence_note( - 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_occurrence_note_flattened_error(): - client = GrafeasClient( - 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_occurrence_note( - grafeas.GetOccurrenceNoteRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_occurrence_note_flattened_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_occurrence_note( - 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_occurrence_note_flattened_error_async(): - client = GrafeasAsyncClient( - 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_occurrence_note( - grafeas.GetOccurrenceNoteRequest(), - name='name_value', - ) - - -def test_get_note(transport: str = 'grpc', request_type=grafeas.GetNoteRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - vulnerability=vulnerability.VulnerabilityNote(cvss_score=0.1082), - ) - response = client.get_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.GetNoteRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -def test_get_note_from_dict(): - test_get_note(request_type=dict) - - -def test_get_note_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 = GrafeasClient( - 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_note), - '__call__') as call: - client.get_note() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.GetNoteRequest() - - -@pytest.mark.asyncio -async def test_get_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.GetNoteRequest): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - )) - response = await client.get_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.GetNoteRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -@pytest.mark.asyncio -async def test_get_note_async_from_dict(): - await test_get_note_async(request_type=dict) - - -def test_get_note_field_headers(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.GetNoteRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_note), - '__call__') as call: - call.return_value = grafeas.Note() - client.get_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_note_field_headers_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.GetNoteRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_note), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - await client.get_note(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_note_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_note( - 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_note_flattened_error(): - client = GrafeasClient( - 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_note( - grafeas.GetNoteRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_note_flattened_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_note( - 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_note_flattened_error_async(): - client = GrafeasAsyncClient( - 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_note( - grafeas.GetNoteRequest(), - name='name_value', - ) - - -def test_list_notes(transport: str = 'grpc', request_type=grafeas.ListNotesRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNotesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.ListNotesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_notes_from_dict(): - test_list_notes(request_type=dict) - - -def test_list_notes_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 = GrafeasClient( - 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_notes), - '__call__') as call: - client.list_notes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.ListNotesRequest() - - -@pytest.mark.asyncio -async def test_list_notes_async(transport: str = 'grpc_asyncio', request_type=grafeas.ListNotesRequest): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNotesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.ListNotesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_notes_async_from_dict(): - await test_list_notes_async(request_type=dict) - - -def test_list_notes_field_headers(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.ListNotesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__') as call: - call.return_value = grafeas.ListNotesResponse() - client.list_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_notes_field_headers_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.ListNotesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNotesResponse()) - await client.list_notes(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_notes_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNotesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_notes( - parent='parent_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].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -def test_list_notes_flattened_error(): - client = GrafeasClient( - 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_notes( - grafeas.ListNotesRequest(), - parent='parent_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_list_notes_flattened_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNotesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNotesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_notes( - parent='parent_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].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_list_notes_flattened_error_async(): - client = GrafeasAsyncClient( - 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_notes( - grafeas.ListNotesRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_notes_pager(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - grafeas.Note(), - ], - next_page_token='abc', - ), - grafeas.ListNotesResponse( - notes=[], - next_page_token='def', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - ], - next_page_token='ghi', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_notes(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, grafeas.Note) - for i in results) - -def test_list_notes_pages(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - grafeas.Note(), - ], - next_page_token='abc', - ), - grafeas.ListNotesResponse( - notes=[], - next_page_token='def', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - ], - next_page_token='ghi', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - ], - ), - RuntimeError, - ) - pages = list(client.list_notes(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_notes_async_pager(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - grafeas.Note(), - ], - next_page_token='abc', - ), - grafeas.ListNotesResponse( - notes=[], - next_page_token='def', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - ], - next_page_token='ghi', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_notes(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, grafeas.Note) - for i in responses) - -@pytest.mark.asyncio -async def test_list_notes_async_pages(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - grafeas.Note(), - ], - next_page_token='abc', - ), - grafeas.ListNotesResponse( - notes=[], - next_page_token='def', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - ], - next_page_token='ghi', - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_notes(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_note(transport: str = 'grpc', request_type=grafeas.DeleteNoteRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.DeleteNoteRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_note_from_dict(): - test_delete_note(request_type=dict) - - -def test_delete_note_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 = GrafeasClient( - 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_note), - '__call__') as call: - client.delete_note() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.DeleteNoteRequest() - - -@pytest.mark.asyncio -async def test_delete_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.DeleteNoteRequest): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.DeleteNoteRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_note_async_from_dict(): - await test_delete_note_async(request_type=dict) - - -def test_delete_note_field_headers(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.DeleteNoteRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_note), - '__call__') as call: - call.return_value = None - client.delete_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_note_field_headers_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.DeleteNoteRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_note), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_note(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_note_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_note), - '__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_note( - 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_note_flattened_error(): - client = GrafeasClient( - 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_note( - grafeas.DeleteNoteRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_note_flattened_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_note), - '__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_note( - 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_note_flattened_error_async(): - client = GrafeasAsyncClient( - 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_note( - grafeas.DeleteNoteRequest(), - name='name_value', - ) - - -def test_create_note(transport: str = 'grpc', request_type=grafeas.CreateNoteRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - vulnerability=vulnerability.VulnerabilityNote(cvss_score=0.1082), - ) - response = client.create_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.CreateNoteRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -def test_create_note_from_dict(): - test_create_note(request_type=dict) - - -def test_create_note_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 = GrafeasClient( - 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_note), - '__call__') as call: - client.create_note() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.CreateNoteRequest() - - -@pytest.mark.asyncio -async def test_create_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.CreateNoteRequest): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - )) - response = await client.create_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.CreateNoteRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -@pytest.mark.asyncio -async def test_create_note_async_from_dict(): - await test_create_note_async(request_type=dict) - - -def test_create_note_field_headers(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.CreateNoteRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_note), - '__call__') as call: - call.return_value = grafeas.Note() - client.create_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_note_field_headers_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.CreateNoteRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_note), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - await client.create_note(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_note_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_note( - parent='parent_value', - note_id='note_id_value', - note=grafeas.Note(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].parent == 'parent_value' - assert args[0].note_id == 'note_id_value' - assert args[0].note == grafeas.Note(name='name_value') - - -def test_create_note_flattened_error(): - client = GrafeasClient( - 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_note( - grafeas.CreateNoteRequest(), - parent='parent_value', - note_id='note_id_value', - note=grafeas.Note(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_note_flattened_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_note( - parent='parent_value', - note_id='note_id_value', - note=grafeas.Note(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].parent == 'parent_value' - assert args[0].note_id == 'note_id_value' - assert args[0].note == grafeas.Note(name='name_value') - - -@pytest.mark.asyncio -async def test_create_note_flattened_error_async(): - client = GrafeasAsyncClient( - 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_note( - grafeas.CreateNoteRequest(), - parent='parent_value', - note_id='note_id_value', - note=grafeas.Note(name='name_value'), - ) - - -def test_batch_create_notes(transport: str = 'grpc', request_type=grafeas.BatchCreateNotesRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateNotesResponse( - ) - response = client.batch_create_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.BatchCreateNotesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.BatchCreateNotesResponse) - - -def test_batch_create_notes_from_dict(): - test_batch_create_notes(request_type=dict) - - -def test_batch_create_notes_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 = GrafeasClient( - 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.batch_create_notes), - '__call__') as call: - client.batch_create_notes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.BatchCreateNotesRequest() - - -@pytest.mark.asyncio -async def test_batch_create_notes_async(transport: str = 'grpc_asyncio', request_type=grafeas.BatchCreateNotesRequest): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateNotesResponse( - )) - response = await client.batch_create_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.BatchCreateNotesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.BatchCreateNotesResponse) - - -@pytest.mark.asyncio -async def test_batch_create_notes_async_from_dict(): - await test_batch_create_notes_async(request_type=dict) - - -def test_batch_create_notes_field_headers(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.BatchCreateNotesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), - '__call__') as call: - call.return_value = grafeas.BatchCreateNotesResponse() - client.batch_create_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_batch_create_notes_field_headers_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.BatchCreateNotesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateNotesResponse()) - await client.batch_create_notes(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_batch_create_notes_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateNotesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.batch_create_notes( - parent='parent_value', - notes={'key_value': grafeas.Note(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].parent == 'parent_value' - assert args[0].notes == {'key_value': grafeas.Note(name='name_value')} - - -def test_batch_create_notes_flattened_error(): - client = GrafeasClient( - 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.batch_create_notes( - grafeas.BatchCreateNotesRequest(), - parent='parent_value', - notes={'key_value': grafeas.Note(name='name_value')}, - ) - - -@pytest.mark.asyncio -async def test_batch_create_notes_flattened_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateNotesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.BatchCreateNotesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_create_notes( - parent='parent_value', - notes={'key_value': grafeas.Note(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].parent == 'parent_value' - assert args[0].notes == {'key_value': grafeas.Note(name='name_value')} - - -@pytest.mark.asyncio -async def test_batch_create_notes_flattened_error_async(): - client = GrafeasAsyncClient( - 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.batch_create_notes( - grafeas.BatchCreateNotesRequest(), - parent='parent_value', - notes={'key_value': grafeas.Note(name='name_value')}, - ) - - -def test_update_note(transport: str = 'grpc', request_type=grafeas.UpdateNoteRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - vulnerability=vulnerability.VulnerabilityNote(cvss_score=0.1082), - ) - response = client.update_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.UpdateNoteRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -def test_update_note_from_dict(): - test_update_note(request_type=dict) - - -def test_update_note_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 = GrafeasClient( - 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_note), - '__call__') as call: - client.update_note() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.UpdateNoteRequest() - - -@pytest.mark.asyncio -async def test_update_note_async(transport: str = 'grpc_asyncio', request_type=grafeas.UpdateNoteRequest): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note( - name='name_value', - short_description='short_description_value', - long_description='long_description_value', - kind=common.NoteKind.VULNERABILITY, - related_note_names=['related_note_names_value'], - )) - response = await client.update_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.UpdateNoteRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == 'name_value' - assert response.short_description == 'short_description_value' - assert response.long_description == 'long_description_value' - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ['related_note_names_value'] - - -@pytest.mark.asyncio -async def test_update_note_async_from_dict(): - await test_update_note_async(request_type=dict) - - -def test_update_note_field_headers(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.UpdateNoteRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_note), - '__call__') as call: - call.return_value = grafeas.Note() - client.update_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_update_note_field_headers_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.UpdateNoteRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_note), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - await client.update_note(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_update_note_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_note( - name='name_value', - note=grafeas.Note(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].name == 'name_value' - assert args[0].note == grafeas.Note(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_note_flattened_error(): - client = GrafeasClient( - 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_note( - grafeas.UpdateNoteRequest(), - name='name_value', - note=grafeas.Note(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_note_flattened_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_note), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_note( - name='name_value', - note=grafeas.Note(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].name == 'name_value' - assert args[0].note == grafeas.Note(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_note_flattened_error_async(): - client = GrafeasAsyncClient( - 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_note( - grafeas.UpdateNoteRequest(), - name='name_value', - note=grafeas.Note(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_list_note_occurrences(transport: str = 'grpc', request_type=grafeas.ListNoteOccurrencesRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_note_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNoteOccurrencesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_note_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.ListNoteOccurrencesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNoteOccurrencesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_note_occurrences_from_dict(): - test_list_note_occurrences(request_type=dict) - - -def test_list_note_occurrences_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 = GrafeasClient( - 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_note_occurrences), - '__call__') as call: - client.list_note_occurrences() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.ListNoteOccurrencesRequest() - - -@pytest.mark.asyncio -async def test_list_note_occurrences_async(transport: str = 'grpc_asyncio', request_type=grafeas.ListNoteOccurrencesRequest): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_note_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNoteOccurrencesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_note_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.ListNoteOccurrencesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNoteOccurrencesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_note_occurrences_async_from_dict(): - await test_list_note_occurrences_async(request_type=dict) - - -def test_list_note_occurrences_field_headers(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.ListNoteOccurrencesRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__') as call: - call.return_value = grafeas.ListNoteOccurrencesResponse() - client.list_note_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_list_note_occurrences_field_headers_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.ListNoteOccurrencesRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNoteOccurrencesResponse()) - await client.list_note_occurrences(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_list_note_occurrences_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNoteOccurrencesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_note_occurrences( - name='name_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].name == 'name_value' - assert args[0].filter == 'filter_value' - - -def test_list_note_occurrences_flattened_error(): - client = GrafeasClient( - 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_note_occurrences( - grafeas.ListNoteOccurrencesRequest(), - name='name_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_list_note_occurrences_flattened_async(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNoteOccurrencesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.ListNoteOccurrencesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_note_occurrences( - name='name_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].name == 'name_value' - assert args[0].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_list_note_occurrences_flattened_error_async(): - client = GrafeasAsyncClient( - 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_note_occurrences( - grafeas.ListNoteOccurrencesRequest(), - name='name_value', - filter='filter_value', - ) - - -def test_list_note_occurrences_pager(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', ''), - )), - ) - pager = client.list_note_occurrences(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, grafeas.Occurrence) - for i in results) - -def test_list_note_occurrences_pages(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - pages = list(client.list_note_occurrences(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_note_occurrences_async_pager(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_note_occurrences(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, grafeas.Occurrence) - for i in responses) - -@pytest.mark.asyncio -async def test_list_note_occurrences_async_pages(): - client = GrafeasAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token='abc', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[], - next_page_token='def', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token='ghi', - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_note_occurrences(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.GrafeasGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.GrafeasGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = GrafeasClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.GrafeasGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = GrafeasClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.GrafeasGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = GrafeasClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.GrafeasGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.GrafeasGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.GrafeasGrpcTransport, - transports.GrafeasGrpcAsyncIOTransport, -]) -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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.GrafeasGrpcTransport, - ) - -def test_grafeas_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.GrafeasTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_grafeas_base_transport(): - # Instantiate the base transport. - with mock.patch('grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.GrafeasTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_occurrence', - 'list_occurrences', - 'delete_occurrence', - 'create_occurrence', - 'batch_create_occurrences', - 'update_occurrence', - 'get_occurrence_note', - 'get_note', - 'list_notes', - 'delete_note', - 'create_note', - 'batch_create_notes', - 'update_note', - 'list_note_occurrences', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_grafeas_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('grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.GrafeasTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_grafeas_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('grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.GrafeasTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - ), - quota_project_id="octopus", - ) - - -def test_grafeas_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('grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.GrafeasTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_grafeas_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) - GrafeasClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_grafeas_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) - GrafeasClient() - adc.assert_called_once_with( - scopes=(), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.GrafeasGrpcTransport, - transports.GrafeasGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_grafeas_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=(), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.GrafeasGrpcTransport, - transports.GrafeasGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_grafeas_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=( -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.GrafeasGrpcTransport, grpc_helpers), - (transports.GrafeasGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_grafeas_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( - "containeranalysis.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( -), - scopes=["1", "2"], - default_host="containeranalysis.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport]) -def test_grafeas_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_grafeas_host_no_port(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='containeranalysis.googleapis.com'), - ) - assert client.transport._host == 'containeranalysis.googleapis.com:443' - - -def test_grafeas_host_with_port(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='containeranalysis.googleapis.com:8000'), - ) - assert client.transport._host == 'containeranalysis.googleapis.com:8000' - -def test_grafeas_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.GrafeasGrpcTransport( - 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_grafeas_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.GrafeasGrpcAsyncIOTransport( - 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.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport]) -def test_grafeas_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.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport]) -def test_grafeas_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_note_path(): - project = "squid" - note = "clam" - expected = "projects/{project}/notes/{note}".format(project=project, note=note, ) - actual = GrafeasClient.note_path(project, note) - assert expected == actual - - -def test_parse_note_path(): - expected = { - "project": "whelk", - "note": "octopus", - } - path = GrafeasClient.note_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_note_path(path) - assert expected == actual - -def test_occurrence_path(): - project = "oyster" - occurrence = "nudibranch" - expected = "projects/{project}/occurrences/{occurrence}".format(project=project, occurrence=occurrence, ) - actual = GrafeasClient.occurrence_path(project, occurrence) - assert expected == actual - - -def test_parse_occurrence_path(): - expected = { - "project": "cuttlefish", - "occurrence": "mussel", - } - path = GrafeasClient.occurrence_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_occurrence_path(path) - assert expected == actual - -def test_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = GrafeasClient.project_path(project) - assert expected == actual - - -def test_parse_project_path(): - expected = { - "project": "nautilus", - } - path = GrafeasClient.project_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_project_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = GrafeasClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = GrafeasClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = GrafeasClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = GrafeasClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = GrafeasClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = GrafeasClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = GrafeasClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = GrafeasClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "cuttlefish" - location = "mussel" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = GrafeasClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = GrafeasClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.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.GrafeasTransport, '_prep_wrapped_messages') as prep: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.GrafeasTransport, '_prep_wrapped_messages') as prep: - transport_class = GrafeasClient.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/grafeas_v1/test_grafeas.py b/tests/unit/gapic/grafeas_v1/test_grafeas.py index 653c12d..1dc5694 100644 --- a/tests/unit/gapic/grafeas_v1/test_grafeas.py +++ b/tests/unit/gapic/grafeas_v1/test_grafeas.py @@ -3654,7 +3654,7 @@ def test_grafeas_grpc_transport_client_cert_source_for_mtls(transport_class): "squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=(), + scopes=None, ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, options=[ @@ -3738,7 +3738,7 @@ def test_grafeas_transport_channel_mtls_with_client_cert_source(transport_class) "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=(), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ @@ -3782,7 +3782,7 @@ def test_grafeas_transport_channel_mtls_with_adc(transport_class): "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, - scopes=(), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[